不区分大小写的搜索 [英] Case-insensitive search
问题描述
我正在尝试使用JavaScript中的两个字符串进行不区分大小写的搜索。
I'm trying to get a case-insensitive search with two strings in JavaScript working.
通常它会是这样的:
var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
/ i
标志用于案例 - 不敏感。
The /i
flag would be for case-insensitive.
但我需要搜索第二个字符串;没有旗帜它完美无缺:
But I need to search for a second string; without the flag it works perfect:
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
如果我将 / i
标志添加到上面的例子它将搜索searchstring而不是变量searchstring中的内容(下一个例子不起作用):
If I add the /i
flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
我如何实现这一目标?
推荐答案
是的,使用 .match
,而不是 .search
。 .match
调用的结果将返回与其自身匹配的实际字符串,但它仍可用作布尔值。
Yeah, use .match
, rather than .search
. The result from the .match
call will return the actual string that was matched itself, but it can still be used as a boolean value.
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
使用这样的正则表达式可能是最简洁,最明显的方法在JavaScript中,但请记住它是正则表达式,因此可以包含正则表达式元字符。如果你想从其他地方获取字符串(例如,用户输入),或者如果你想避免必须逃避许多元字符,那么你最好使用 indexOf
像这样:
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf
like this:
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');
}
这篇关于不区分大小写的搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!