0

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

我正在使用正则表达式和 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);
    }
}
}

我的问题是每次调用该函数以仅用一个字母替换表达式时,即使在一个单词中,也会在该字母第一次出现时进行替换。我以为用 before 和 after 查找那封信\s可以解决它,但事实并非如此。

4

4 回答 4

2

如果你只想匹配一个单词,你应该放在\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;
}
于 2012-07-23T11:57:02.823 回答
1

您需要向g正则表达式添加一个(全局)修改,以便它将替换所有出现并使用\b而不是\s标记单词边界。

source = new Array(/\brsrs\b/g,/\bñ\b/g, etc 

附带说明一下,由于您所有的正则表达式都遵循相同的模式,因此这样做可能更容易:

source = new Array( 'rsr', 'ñ', 'naum', etc );

if( myregex = newtext.match( new Regexp( "\b"+source[i]+"\b", 'g' ) ) ) {
    ...
于 2012-07-23T12:01:14.367 回答
0

如果通过“实时替换”你的意思是在每次击键时调用函数替换,那么最后的 \b 对你没有帮助,你确实应该使用 \s。但是,在您的替换功能中,您正在向文本字段值添加一个空格,以便您的单字符词触发替换。

这是我对您的代码的重构:

(function () { // wrap in immediate function to hide local variables
  source = [ [/\brsrs\s$/, "risos"], // place reg exp and replacement next to each other
             [/\b(ñ|naum)\s$/, "não"], // note combined regexps
             [/\bvc\s$/, "você"]
             // ...
           ]; // not also use of array literals in place of new Array

  document.getElementById ("translation"​​​​​​​).addEventListener ('keyup', function (ev) {
    var t =  this.value  // fetch text area value
      , m
      , i = source.length;

    while (i--) // for each possible match
      if ((m = t.match(source[i][0]))) { // does this one match ?
        // replace match : first remove the match string (m[0]) from the end of 
        // the text string, then add the replacement word followed by a space
        this.value = t.slice (0, -m[0].length) + source[i][1] + ' '; 
        return; // done
      }
  }, false);  
}) ();​

小提琴是:http: //jsfiddle.net/jFYuV

于 2012-07-23T12:53:04.597 回答
0

以一种不同的风格,您可以创建一个封装替换列表的函数:

var substitutions = {
    "rsrs": "risos",
    "ñ": "não",
    "naum": "não",
    "vc": "você",
    // ...
};

var createSubstitutionFunction = function(subs) {
    var keys = [];
    for (var key in subs) {
        if (subs.hasOwnProperty(key)) {
            keys[keys.length] = key;
        }
    }
    var regex = new RegExp("\\b" + keys.join("\\b|\\b") + "\\b", "g");
    return function(text) {
        return text.replace(regex, function(match) {
            return subs[match];
        });
    };
};

var replacer = createSubstitutionFunction(substitutions);

你会像这样使用它:

replacer("Some text with rsrs and naum and more rsrs and vc")
// ==> "Some text with risos and não and more risos and você"
于 2012-07-23T13:27:42.717 回答