我试图得到一个不区分大小写的搜索与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);

我怎样才能做到这一点呢?


当前回答

取代

var result= string.search(/searchstring/i);

with

var result= string.search(new RegExp(searchstring, "i"));

其他回答

取代

var result= string.search(/searchstring/i);

with

var result= string.search(new RegExp(searchstring, "i"));

假设我们想要在字符串变量大海捞针。这里有三个陷阱:

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);

我在尝试区分大小写的字符串搜索,我尝试了

 var result = string.toLowerCase().match(searchstring) 

var result= string.search(new RegExp(searchstring, "i"));

但我做了一些小修改,对我有用

var result = string.match(new RegExp(searchstring, "i"));

这也可以是小写,大写或组合

不区分大小写的比较有两种方式:

将字符串转换为大写,然后使用严格操作符(===)进行比较。 使用字符串方法进行模式匹配: 使用"search"字符串方法进行不区分大小写的搜索。

<!doctype html > < html > < >头 <脚本> //第一种方式 Var a = "苹果"; var b = "苹果"; if (a.toUpperCase() === b.toUpperCase()) { alert("平等"); } / / 2路 var a = "无效"; document . write (a.search(/空/我)); > < /脚本 > < /头 < / html >

ES6 +:

let string="Stackoverflow is the BEST";
let searchstring="best";


let found = string.toLowerCase()
                  .includes(searchstring.toLowerCase());

includes()如果searchString出现在一个或多个位置则返回true,否则返回false。