此问题在此处已有答案:
Escape string for use in Javascript regex [duplicate](1个答案)
2天前关闭。
在我的网页中,我有一个“查找”功能,用户在“查找”对话框中键入一些文本,它会获得在变量中可以找到文本的索引。事先我既不知道要搜索的文本,也不知道用户要查找的文本。我为他们提供了一个选项,以确定是否匹配大小写,以及是否仅查找整个单词(例如,如果他们输入“manager”,则“manager”是否应该匹配。
下面的代码是我的代码的精简版本,只包含了与我的问题相关的内容。在这个例子中,我想在“This is a test.(10)"中查找“(1)”。我期望在执行后索引将是-1,但它是16,这是“1”的索引。
你能告诉我为什么这个不起作用,什么会起作用?谢谢。
let matchCase = false;
let wholeWord = false;
let index = 0;
let options = "";
let phrase = "(1)";
phrase = phrase.replaceAll(String.fromCharCode(160), "\\s");
if (!matchCase) options += "i";
if (wholeWord) phrase = "\\b" + phrase + "\\b";
let regex = new RegExp(phrase, options);
let text = "This is a test.(10)";
let index = text.search(regex);
console.log(index);
1条答案
按热度按时间w8biq8rn1#
您需要在输入中转义正则表达式元字符,如
(
。