gpt4 book ai didi

javascript - 从正则表达式文字转换为RegExp构造函数

转载 作者:行者123 更新时间:2023-11-30 12:31:17 25 4
gpt4 key购买 nike

我正在尝试制作一个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..
}

最佳答案

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

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

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

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

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

关于javascript - 从正则表达式文字转换为RegExp构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com