String.replace
方法接受回調函數作爲其第二個參數。在回調中,您可以在返回替換字符串之前執行所需的任何特殊處理。
var translations = {
users: "utilisateurs",
apples: "pommes",
...
};
// You could generate the regular expression from the object above
// or if the number of words is high, not use regular expressions at all.
s = s.replace(/users|apples|oranges/gi, function (match) {
return matchCase(translations[match], match);
});
function getCase(ch) {
return ch == ch.toUpperCase()
? "Upper"
: "Lower";
}
function convertCase(s, case) {
return s["to" + case + "Case"]();
}
function matchCase(s, target) {
return convertCase(s[0], getCase(target[0]))
+ convertCase(s.substr(1), getCase(target[1]));
}
此主題不回答問題,但可能會給一些有用的信息,但仍然http://stackoverflow.com/questions/2332811/capitalize-words-in-string – Orbit 2011-03-01 18:27:44
我需要噸他作爲一個函數,2個參數,原始的,新的,然後如何使新詞與第一個詞具有相同的大小寫。 – crosenblum 2011-03-01 18:29:47
所以你想'用戶'轉化爲'Utilisateurs' ...你想'UseRs'轉化爲'UtiLisateurs'或其他?你想如何處理'USERS'?大寫整個翻譯的字符串? – 2011-03-01 18:52:43