Possible Duplicate:
Is there a RegExp.escape function in Javascript?
我目前正在使用:var keywords = new RegExp(req.params.keywords, 'i');
问题是,如果 req.params.keywords == '.*'
,这将匹配任何内容,我想要的是它匹配 .*
从字面上看,如 \.\*\
有没有比用 \
转义每个传递的单个字符更优雅的解决方案? ?
最佳答案
如果您想按字面匹配,而不是使用字符串中包含的正则表达式,请不要使用正则表达式。使用字符串 indexOf()
函数查看一个字符串是否包含在另一个字符串中。
对于不区分大小写的匹配,您可以在匹配之前将每个字符串转换为小写。
var searchForString = req.params.keywords.toLowerCase();
var searchInString = xxx.toLowerCase();
if (searchInString.indexOf(searchForString) >= 0) {
... then it matches ...
}
关于字符串文字的 JavaScript 正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14607884/