Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

javascript - regex.test V.S. string.match以了解字符串是否与正则表达式匹配(regex.test V.S. string.match to know if a string matches a regular expression)

Many times I'm using the string match function to know if a string matches a regular expression.

(很多时候我正在使用字符串match函数来知道字符串是否与正则表达式匹配。)

if(str.match(/{regex}/))

Is there any difference between this:

(这有什么区别:)

if (/{regex}/.test(str))

They seem to give the same result?

(他们似乎给出了相同的结果?)

  ask by gdoron translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basic Usage(基本用法)

First, let's see what each function does:

(首先,让我们看看每个函数的作用:)

regexObject .

(regexObject 。)

test ( String )

(测试字符串 ))

Executes the search for a match between a regular expression and a specified string.

(执行正则表达式与指定字符串之间匹配的搜索。)

Returns true or false .

(返回truefalse 。)

string .

(字符串 。)

match ( RegExp )

(匹配RegExp ))

Used to retrieve the matches when matching a string against a regular expression.

(用于在将字符串与正则表达式匹配时检索匹配项。)

Returns an array with the matches or null if there are none.

(返回带匹配的数组,如果没有则返回null 。)

Since null evaluates to false ,

(由于null计算结果为false ,)

if ( string.match(regex) ) {
  // There was a match.
} else {
  // No match.
} 

Performance(性能)

Is there any difference regarding performance?

(表现有什么不同吗?)

Yes .

(是的)

I found this short note in the MDN site :

(我在MDN网站上发现了这个简短的说明:)

If you need to know if a string matches a regular expression regexp, use regexp.test(string).

(如果您需要知道字符串是否与正则表达式regexp匹配,请使用regexp.test(string)。)

Is the difference significant?

(差异显着吗?)

The answer once more is YES !

(答案再一次是肯定的 !)

This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:

(我把这个jsPerf放在一起显示差异是~30% - ~60%取决于浏览器:)

测试vs匹配|性能测试

Conclusion(结论)

Use .test if you want a faster boolean check.

(如果您想要更快的布尔检查,请使用.test 。)

Use .match to retrieve all matches when using the g global flag.

(使用.match在使用g全局标志时检索所有匹配项。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...