从正则表达式文字切换到RegExp构造函数

时间:2014-12-23 18:27:26

标签: javascript regex escaping

我试图创建一个JS函数,选择以变量字(3或4个字母)开头的所有单词,然后加粗它们。我发现了一个合适的正则表达式here但是当我尝试调整它时(特别是当我使用new RegExp时)时,它已经不再适用了。

JSfiddle是here

感谢您的帮助!

以下是HTML代码:

<div id="text1">#hallo, this is a test #john #doe with myWordOfTheYear</div>
<input type="text" id="input1" onkeyup="searchC(this.value);searchD(this.value);" size="100"/> <br />
Result of searchA function: <div id="testA"></div>
Result of searchB function: <div id="testB"></div>
Result of searchC function: <div id="testC"></div>

<script>searchA();searchB();</script>

JS部分:

//function created from http://jsfiddle.net/BUC7L/
function searchA() {
    var s = document.getElementById('text1').innerHTML ;
    var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = [];
    while (match = re.exec(s)) {
      matches.push(match[0]);
    }
    document.getElementById('testA').innerHTML = matches;
}

//function where I just tried to rewrite it with 'RegExp'. This function does not work
function searchB() {
    var s = document.getElementById('text1').innerHTML ;
    var re = new RegExp("(?:^|\W)#(\w+)(?!\w)",g);
    var match, matches = [];
    while (match = re.exec(s)) {
      matches.push(match[0]);
    }
    document.getElementById('testB').innerHTML = matches;
}

//function that shows a bit more my goal but does not work.
function searchC(wordInput) {
    var s = document.getElementById('text1').innerHTML ;
    var re = new RegExp("(?:^|\W)"+wordInput+"(\w+)(?!\w)","g");
    var match, matches = [];
    while (match = re.exec(s)) {
      matches.push(match[0]);
    }
    document.getElementById('testC').innerHTML = matches;
}

//function that shows my specific goal but does not work.
function searchD(wordInput) {
    var s = document.getElementById('text1').innerHTML ;
    var re = new RegExp("(?:^|\W)"+wordInput+"(\w+)(?!\w)","g");
    document.getElementById('text').innerHTML.replace(re,'<b>'+re+'</b>'); //I know this line cannot work but I don't manage to find a way to do it, it's just to show what I want..
}

2 个答案:

答案 0 :(得分:2)

在字符串模式中使用时,您需要转义用于字符类的反斜杠。否则,JavaScript的字符串文字解析会将"\W"转换为字符串"W"(因为它不是可识别的转义序列),这对RegExp构造函数没有特别的意义,只是匹配W.

你还需要引用flag参数;裸g看起来像一个符号,而不是它需要的字符串,并且可能没有g名称的变量,所以它只是传入undefined

请注意,正则表达式文字语法(例如searchA)在任何步骤都不使用字符串,因此不使用任何字符串。对于字符串来自其他地方的情况,构造函数最有用:用户输入,配置文件,带有一些现有数据的字符串连接等等。

因此,在searchB中,正确的语法是:

    var re = new RegExp("(?:^|\\W)#(\\w+)(?!\\w)", "g");

答案 1 :(得分:1)

你需要转义两次,g需要是一个字符串:

var re = new RegExp("(?:^|\\W)#(\\w+)(?!\\w)",'g');