I have a set of strings that I need to replace, but I need to keep the case of letters.
Both the input words and output words are of the same length.
For example, if I need to replace "abcd" with "qwer", then the following should happen:
"AbcD" translates to "QweR" "abCd" translates to "qwEr"
and so on.
Right now I'm using JavaScript's replace
, but capital letters are lost on translation.
r = new RegExp( "(" + 'asdf' + ")" , 'gi' ); "oooAsdFoooo".replace(r, "qwer");
Any help would be appreciated.
The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.
Here’s a helper:
function matchCase(text, pattern) { var result = ''; for(var i = 0; i < text.length; i++) { var c = text.charAt(i); var p = pattern.charCodeAt(i); if(p >= 65 && p < 65 + 26) { result += c.toUpperCase(); } else { result += c.toLowerCase(); } } return result; }
Then you can just:
"oooAsdFoooo".replace(r, function(match) { return matchCase("qwer", match); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With