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

[REG]正则表达式(JS) #15

Open
cookiepool opened this issue Oct 11, 2019 · 0 comments
Open

[REG]正则表达式(JS) #15

cookiepool opened this issue Oct 11, 2019 · 0 comments
Labels
前端相关 前端相关

Comments

@cookiepool
Copy link
Owner

cookiepool commented Oct 11, 2019

  • JS的正则表达式的g参数表示全局匹配,一般如果不用g参数只会匹配到第一个跟正则匹配的字符,其它的会忽略掉,比如这种:
' hello world '.replace(/\s*/, '')
输出"hello world ",只匹配了第一个空格并替换

用全局匹配可以全部替换

' hello world '.replace(/\s*/g, '')
输出"helloworld",空格都替换掉了

  • 构建正则表达式,我们一般是这样做的:
let reg = /^\s*/;

使用RegExp类来做的话,我们需要构建一个实例,像这样:

let reg = new RegExp('^\\s*') // 这种直接使用字符串,斜杠要多打一个,不然生成的正则表达式没转义符

当然这样也行:

let reg = new RegExp(/^\s*/);
  • 为何精确匹配需要在正则表达式首位分别加^和$。
    给个栗子就清楚了,如下:
// 有如下正则
/.{2}/

这个表示任意符号匹配两个,此时未加^和$,我们给出wweerr,它会把ww ee rr分别都匹配到,所以要精确匹配需要加^和$,像这样/^.{2}$/它只会匹配两个,多的都不认!

@cookiepool cookiepool added the 前端相关 前端相关 label Nov 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
前端相关 前端相关
Projects
None yet
Development

No branches or pull requests

1 participant