我正在使用正则表达式查找某个字符串在另一个字符串中的所有出现,同时忽略任何空格和不同的大小写。
下面是我当前的代码:
var str = word.substring(0,1)+"\\s*";
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
str = str + word.substring(word.length - 1,word.length);
var regEx = new RegExp(str, "gi");
一个例子是 if var word = "foobar"
:
var word = "foobar";
var str = word.substring(0,1)+"\\s*"; // declares the string as "f\\s*"
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*"; // will add every character together with \\s* to 'str' like this: "f\\s*o\\s*o\\s*b\\s*a\\s*"
str = str + word.substring(word.length - 1,word.length); // will add the last character without \\s* like this: "f\\s*o\\s*o\\s*b\\s*a\\s*r"
var regEx = new RegExp(str, "gi"); // outputs /f\s*o\s*o\s*b\s*a\s*r/gi
这是可行的,但感觉不是解决问题的最佳方法。如果有人对此有更好的解决方案,我将不胜感激。
最佳答案
您可以使用split
和join
来简化这个:
var word = "foobar";
var regex = new RegExp(word.split('').join('\\s*'), 'gi');
//=> /f\s*o\s*o\s*b\s*a\s*r/gi
关于javascript - 在javascript中忽略正则表达式中的空格和不同大小写的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36508682/