Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replace all with case insensitive and keeping correct case in original string

Tags:

javascript

My problem is i want to do something like this:

Javascript vaja => <b>Ja</b>vascript va<b>ja</b> i.e i have a query string(ja) and i want to replace all the occurances(case insensitive) of that query string in a bigger string (Javascript vaja).

The closest solution i have right now is:

"Javascript vaja".replace(/ja/gi, '<b>ja</b>');

which gives me:

"<b>ja</b>vascript va<b>ja</b>"

but what i need is:

Javascript vaja => <b>Ja</b>vascript va<b>ja</b>

one solution that i have in mind is to keep the indexes of upcase letters before replacement and then re replace them. But that is way too hacky. I am pretty sure i am not the first one trying this and pretty sure there is some elegant and simpler solution hidden somewhere.

like image 636
Sahil Dhankhar Avatar asked Oct 03 '13 14:10

Sahil Dhankhar


People also ask

Is replace case-sensitive in JS?

In this example, we will see that replace() method is case-sensitive. Output: Learn Node. js on Javatpoint.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

Is there a Replace All in JavaScript?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.

What is $1 in replace JavaScript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.


1 Answers

Simply use a capturing group:

"Javascript vaja".replace(/(ja)/gi, '<b>$1</b>');

See this working demo.

Edit: Read more about capturing groups here.

like image 161
theftprevention Avatar answered Oct 08 '22 19:10

theftprevention