gpt4 book ai didi

javascript - 正则表达式测试VS string.match 知道一个字符串是否匹配一个正则表达式

转载 作者:IT老高 更新时间:2023-10-28 13:12:09 29 4
gpt4 key购买 nike

很多时候我使用字符串 match 函数来判断字符串是否匹配正则表达式。

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

这有什么区别:

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

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

最佳答案

基本用法

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

regexObject. test (字符串)

Executes the search for a match between a regular expression and a specified string. Returns true or false.

字符串. match (正则表达式)

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 的计算结果为 false

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

性能

在性能方面有什么不同吗?

是的。我在 MDN site 中找到了这个简短的说明:

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

差异显着吗?

答案再次是YES!这个jsPerf我汇总显示差异为 ~30% - ~60%,具体取决于浏览器:

test vs match | Performance Test

结论

如果您想要更快的 bool 检查,请使用 .test。使用 g 全局标志时,使用 .match 检索所有匹配项。

关于javascript - 正则表达式测试VS string.match 知道一个字符串是否匹配一个正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10940137/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com