用javascript中的数组替换字符串中的多个单词

时间:2012-06-29 17:44:20

标签: javascript arrays

让我说我正在制作一个翻译系统,它将数组键中匹配的所有单词替换为匹配数组键的值,让我们说

translate =
  saya: "i",
  jalan: "walk",
  hutan: "forest",
  beli: "buy",
  ke: "to",
  apel: "apple",
};

string = "SaYa JaLan ke hutan beli Apel" // case insensitive

应该是

string = "I walk to forest buy apple" // the translated string

我们怎样才能在javascript中做到这一点?在函数中,我们可以将其称为

translated = translate(string) // returns the translated string

2 个答案:

答案 0 :(得分:2)

function translate(txt) {
    var translate = {
        saya: "i",
        jalan: "walk",
        hutan: "forest",
        beli: "buy",
        ke: "to",
        apel: "apple"
    };

    for (var key in translate) {
        txt = txt.replace(new RegExp(key, "ig"), translate[key]);
    }
    return txt.charAt(0).toUpperCase() + txt.slice(1);  //Capitalize the first
}                                                          // letter.

var translated = translate("SaYa JaLan ke hutan beli Apel");
//"I walk to forest buy apple" 

演示:http://jsfiddle.net/DerekL/2ucEk/

答案 1 :(得分:-1)

JS noobie我自己,但我认为这应该有用。单词不同但过程相同

    lexicon = new Object();
lexicon.merry = "god";
lexicon.christmas = "jul";
lexicon.and = "och";
lexicon.happy = "gott";
lexicon.new = "nytt";
lexicon.year = "ar";

function translate(){

    //use to show translation:
    //have a merry christmas and a fun new year!
    var myString = document.getElementById('input').value;

    myString = myString.replace(/merry/g, lexicon.merry);
    myString = myString.replace(/christmas/g, lexicon.christmas);
    myString = myString.replace(/and/g, lexicon.and);
    myString = myString.replace(/happy/g, lexicon.happy);
    myString = myString.replace(/new/g, lexicon.new);
    myString = myString.replace(/year/g, lexicon.year);

    document.write(myString);
}