gpt4 book ai didi

javascript - 使用 Javascript 实时替换正则表达式

转载 作者:行者123 更新时间:2023-11-28 20:58:36 25 4
gpt4 key购买 nike

我正在编写一段代码,用于在用户键入时实时替换文本字段中的特定单词。

我正在使用正则表达式和 JavaScript:第一个数组包含要查找的正则表达式,第二个数组包含应替换它们的单词。

source = new Array(/\srsrs\s/,/\sñ\s/,/\snaum\s/,/\svc\s/,/\scd\s/,/\sOq\s/,/\soke\s/,/\so\sq\s/,
/\soque\s/,/\soqe\s/,/\spq\s/,/\sq\s/,/\sp\/\s/g,/\spra\s/,/\sp\s/,/\stbm\s/,
/\stb\s/,/\std\s/,/\sblz\s/,/\saki\s/,/\svlw\s/,/\smara\s/,/\sqlq\s/,/\sqq\s/,
/\srpz\s/,/\smsm\s/,/\smto\s/,/\smtu\s/,/\sqro\s/,/\sqdo\s/,/\sqd\s/,/\sqnd\s/,
/\sqto\s/,/\sqm\s/,/\sjah\s/, /\sc\/\s/,/\scmg\s/,/\s\+\sou\s\-\s/,/\sflw\s/,
/\sxau\s/,/\sto\s/,/\sta\s/);
after = new Array("risos","não","não","você","cadê","o que","o que","o que","o que","o que","porque",
"que","para","para","para","também","também","tudo","beleza","aqui","valeu","maravilhoso",
"qualquer","qualquer","rapaz","mesmo","muito","muito","quero","quando","quando","quando",
"quanto","quem","Já","com","comego","mais ou menos","falow","tchau","estou","está");

这是执行替换的函数:

function replacement(){
for(i=0; i<source.length; i++){
newtext = " "+document.getElementById("translation").value+" ";
console.log(newtext);
if(myregex = newtext.match(source[i])){
newafter = after[i];
rafael = myregex+" ";
document.getElementById("translation").value = document.getElementById("translation").value.replace(rafael, newafter);
}
}
}

我的问题是,每次调用函数来替换仅包含一个字母的表达式时,都会在该字母第一次出现时进行替换,即使是在一个单词中也是如此。我以为在前后查找带有 \s 的字母就能解决问题,但事实并非如此。

最佳答案

如果您只想匹配一个单词,则应该在(单词边界)之前和之后放置 \b。这将确保您不会匹配部分单词。另请注意,您通过连接字符串来破坏正则表达式。试试这个:

var in = document.getElementById("translation").value;
if( in.charAt(in.length-1) == " ") { // user has just finished typing a word
// this avoids interrupting the word being typed
var l = source.length, i;
for( i=0; i<l; i++) in = in.replace(source[i],after[i]);
document.getElementById("translation").value = in;
}

关于javascript - 使用 Javascript 实时替换正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11612029/

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