2012-07-23 102 views
0

我正在为用户输入的文本字段中的特定单词进行实时替换编写代码。用Javascript替换正则表达式

我正在使用正则表达式和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来解决它,但它没有。

+0

如果在用户仍然键入时替换“live”,则必须在使用开始键入之前对字符串执行替换,而不是一次又一次地替换已经替换的结果字符串。 – Bergi 2012-07-23 12:59:10

回答

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

+0

谢谢!这就像一个魅力。 我真的不明白这一行的逻辑: this.value = t.slice(0,-m [0] .length)+ source [i] [1] +''; 你能解释给我吗? – Tomcatom 2012-07-23 13:17:41

+0

添加了一些意见,希望他们帮助。感谢您的支持。我还在RegExp的末尾添加了$,以确保您只在文本末尾替换字符串;用户可以返回并编辑文本以达到他想要的任何内容,而不会受到“翻译”的困扰。 – HBP 2012-07-23 13:44:57

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

您需要添加一个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'))) { 
    ... 
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ê"