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.
In this example, we will see that replace() method is case-sensitive. Output: Learn Node. js on Javatpoint.
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.
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.
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.
Simply use a capturing group:
"Javascript vaja".replace(/(ja)/gi, '<b>$1</b>');
Edit: Read more about capturing groups here.
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