我有以下代码:
var stringToMatch = "De$mond. \(blah)";
var pattern = "^" + stringToMatch;
var regex = new RegExp(pattern, "i");
return regex.test("testing De$mond.");
现在我需要stringToMatch
在使用它之前逃脱pattern
如果我理解正确,我在此处找到的解决方案建议使用此方法:
var stringToMatch = "De$mond. \(blah)";
stringToMatch = stringToMatch.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var pattern = "^" + stringToMatch;
var regex = new RegExp(pattern, "i");
return regex.test("testing De$mond.");
为什么我不能简单地转义所有字符stringToMatch
呢?
例如
var stringToMatch = "De$mond. \(blah)";
var stringToMatchAsArrayOfChars = [];
for (var i = 0; i < stringToMatch.length; i++)
{
stringToMatchAsArrayOfChars.push(stringToMatch.substr(i, 1));
}
var stringToMatchEscaped = "";
for (var i = 0; i < stringToMatchAsArrayOfChars.length; i++)
{
if (stringToMatchAsArrayOfChars[i] !== " ")
{
stringToMatchEscaped = stringToMatchEscaped + "\\" + stringToMatchAsArrayOfChars[i];
}
else
{
stringToMatchEscaped = stringToMatchEscaped + " ";
}
}
var pattern = "^" + stringToMatch;
var regex = new RegExp(pattern, "i");
return regex.test("testing De$mond.");
我知道上述方法要冗长得多,但它的基本作用是:
var stringToMatchEscaped = "\D\e\$\m\o\n\d\. \\\(\b\l\a\h\)";
但它不起作用。这是为什么?
stringToMatch
而且,除了我提供的链接中建议的方法之外,还有其他方法可以逃脱吗?即没有指定要转义的字符,就像它正在完成的那样/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g
?