2

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

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

4

2 回答 2

3
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/

于 2012-06-29T17:48:51.963 回答
-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);
}
于 2012-06-29T17:49:25.100 回答