Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy case pattern when doing string replace?

For example if a word is "Users" and the replacement is "utilisateurs", is there some kind of function that will allow me to conver the replacement string to the same level of capitals/non-capitals as the original word?

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

Now I just want to make sure as the final and professional touch, is to make sure the case of the translated/replaced words, match the case of the original words/phrases.

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

I want this to be as a function

function CopyCase(original,new) {

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

Only not sure how to do that.

like image 993
crosenblum Avatar asked May 23 '26 12:05

crosenblum


1 Answers

Here's a function that will handle cases without internal capitalization:

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.
like image 94
harpo Avatar answered May 26 '26 01:05

harpo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!