我试图得到一个不区分大小写的搜索与JavaScript工作的两个字符串。
通常是这样的:
var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
/i标志不区分大小写。
但我需要寻找第二根弦;如果没有国旗,它就完美了:
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
如果我在上面的例子中添加/ I标志,它将搜索searchstring,而不是变量“searchstring”中的内容(下一个例子不工作):
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
我怎样才能做到这一点呢?
是的,使用。match,而不是。search。match调用的结果将返回匹配的实际字符串本身,但它仍然可以用作布尔值。
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
使用这样的正则表达式可能是JavaScript中最整洁、最明显的方法,但请记住,它是正则表达式,因此可能包含正则元字符。如果你想从其他地方获取字符串(例如,用户输入),或者如果你想避免转义大量元字符,那么你可能最好像这样使用indexOf:
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
假设我们想要在字符串变量大海捞针。这里有三个陷阱:
Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.
考虑到第(1)和(2)点,一个例子是:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);