2012-07-23 111 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ê"