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

时间:2012-07-23 11:55:20

标签: javascript regex

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

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

我的问题是每次调用函数来替换只有一个字母的表达式时,即使在一个单词中,也会在第一次出现该字母时进行替换。我认为在{和}之前和之后寻找那封信会解决它,但事实并非如此。

4 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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' ) ) ) {
    ...

答案 2 :(得分: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

答案 3 :(得分:0)

somewhat different style中,您可以创建一个封装替换列表的函数:

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ê"
相关问题