如何在进行字符串替换时复制大小写模式?

时间:2011-03-01 18:23:39

标签: javascript jquery string

例如,如果一个单词是“Users”而替换是“utilisateurs”,是否有某种函数可以让我将替换字符串转换为与原始单词相同的大写/非大写字母级别?

这是使用jquery,textnodes,精确和部分字符串匹配的主要语言翻译的最后一部分。

现在我只想确保作为最终和专业的触摸,确保翻译/替换的单词的情况与原始单词/短语的情况相符。

我不确定如何将此作为替换电话应用。

我希望这是一个功能

function CopyCase(original,new) {

    // copy the case of the original to the new
}

只是不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

这是一个处理没有内部大写的情况的函数:

function caseWord(word, upper) {
    return String.prototype[ upper ? "toUpperCase" : "toLowerCase"].apply(word[0]) + word.slice(1);
}
function caseReplace(s, fromWord, toWord) {
    return s.replace(caseWord(fromWord), caseWord(toWord))
            .replace(caseWord(fromWord, true), caseWord(toWord, true));
}

console.log(caseReplace("The users have joined the Users union.", "users", "utilisateurs"))
console.log(caseReplace("The lovers have joined the Lovers union.", "lovers", "amants"))

// The utilisateurs have joined the Utilisateurs union.
// The amants have joined the Amants union.

答案 1 :(得分:0)

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]));
}

答案 2 :(得分:0)

function matchCase (word1, word2) {
  //   1) Words starting with two capital letters are assumed to be all caps.
  //   2) Words starting with two lower case letters are assumed to be all lower case.
  //   3) Words starting with an upper case followed by a lowercase letter are
  //      all lower case except the first letter.

   return word1[0] === word1[0].toLowerCase () ? word2.toLowerCase () :
          word1[1] === word1[1].toLowerCase () ? word2[0].toUpperCase () + word2.slice (1).toLowerCase () :
            word2.toUpperCase ();  
}

matchCase ('Word', 'mot')
"Mot"
matchCase ('WOrd', 'mot')
"MOT"
matchCase ('word', 'mot')
"mot"
matchCase ('wOrD', 'mot')
"mot"
matchCase ('woRD', 'mot')
"mot"

编辑更改小写测试,现在应该是语言不可知的(如果底层的toLowerCase函数是)