Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive replace all

Tags:

javascript

I am looking for any implementation of case insensitive replacing function. For example, it should work like this:

'This iS IIS'.replaceAll('is', 'as'); 

and result should be:

'Thas as Ias' 

Any ideas?

UPDATE:

It would be great to use it with variable:

var searchStr = 'is'; 'This iS IIS'.replaceAll(searchStr, 'as'); 
like image 874
Sergey Metlov Avatar asked Sep 05 '11 22:09

Sergey Metlov


People also ask

Is replace in Java case-sensitive?

Case insensitively replaces all occurrences of a String within another String.

Is replace in python case-sensitive?

Is the String replace function case sensitive? Yes, the replace function is case sensitive. That means, the word “this” has a different meaning to “This” or “THIS”. In the following example, a string is created with the different case letters, that is followed by using the Python replace string method.

How do you make a replaceAll case insensitive in Java?

Regular Expression"; String result = sentence. replaceAll("work", "hard work"); System. out. println("Input sentence : " + sentence); System.


2 Answers

Try regex:

'This iS IIS'.replace(/is/ig, 'as'); 

Working Example: http://jsfiddle.net/9xAse/

e.g:
Using RegExp object:

var searchMask = "is"; var regEx = new RegExp(searchMask, "ig"); var replaceMask = "as";  var result = 'This iS IIS'.replace(regEx, replaceMask); 
like image 110
Chandu Avatar answered Sep 24 '22 17:09

Chandu


String.prototype.replaceAll = function(strReplace, strWith) {     // See http://stackoverflow.com/a/3561711/556609     var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');     var reg = new RegExp(esc, 'ig');     return this.replace(reg, strWith); }; 

This implements exactly the example you provided.

'This iS IIS'.replaceAll('is', 'as'); 

Returns

'Thas as Ias' 
like image 31
Ben Avatar answered Sep 24 '22 17:09

Ben