How to copy a pattern template when replacing a string?

For example, if the word is "Users" and the replacement is "utilisateurs", is there any function that will allow me to convert the replacement string to the same capital / non-capital level as the source word?

This is the final part of the main language translation using jquery, textnodes, exact and partial string matching.

Now I just want to make sure that the last and professional touch is to make sure that the case of translated / substituted words matches the case of original words / phrases.

I am not sure how I can apply this as a replacement call.

I want it to be as a function

function CopyCase(original,new) {

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

Just don’t know how to do it.

+3
source share
3

, :

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

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

Edited to change the test for lowercase, which should now be an agnostic of the language (if the base function toLowerCase)

0
source

Source: https://habr.com/ru/post/1795568/


All Articles