Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

练习题1.找出字符串包含的所有连续的数字 #12

Open
chenhuiYj opened this issue Jun 16, 2020 · 0 comments
Open

练习题1.找出字符串包含的所有连续的数字 #12

chenhuiYj opened this issue Jun 16, 2020 · 0 comments

Comments

@chenhuiYj
Copy link
Owner

chenhuiYj commented Jun 16, 2020

编写一个函数 handle ,函数接受一个字符串,找出该字符串里面所由N(N>1)位连续数字组成的数值,

handle('asd123456789asdwa1234sdw578q6e')
// result:   ['123456789','1234']

方法一

function handle(str){
    let _strNumber='123456789'
    let arr=str.replace(/\D+/g,' ').split(/\s+/)
    return arr.filter(item=>item.length>0&&_strNumber.includes(item))
}

//或者缩写成一行代码,但是不建议这样写,因为你链式调用太长,可读性和维护性变差
function handle(str){
    return str.replace(/\D+/g,' ').split(/\s+/).filter(item=>item.length>0&&'123456789'.includes(item))
}

方法二

function handle(str){
    return str.match(/\d+/g,' ').filter(item=>item.length>1&&'123456789'.includes(item))
}

然后,如果要对题目进行改一下,比如上面的字符串,有 578 这个片段,虽然整个不是连续的数字,但是 78 是连续的,如果要兼容这种情况呢?

function handle(str){
   return str.match(/(0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9))\d+/g)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant