Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text but keep case

Tags:

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.

like image 225
ignacio.munizaga Avatar asked Jun 23 '13 19:06

ignacio.munizaga


People also ask

Does replace replace all occurrences?

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.


1 Answers

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); }); 
like image 136
Ry- Avatar answered Sep 18 '22 00:09

Ry-