17

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.

Sahil Dhankhar
  • 3,596
  • 2
  • 31
  • 44
  • Why not just execute two case-sensitive replace() calls? – fred02138 Oct 03 '13 at 14:32
  • i am not pretty sure what your solution is but i want to handle cases like : `Bavascript vaba => Bavascript vaba` and replacing iteratively will crete problems in this case. – Sahil Dhankhar Oct 03 '13 at 14:38

2 Answers2

24

Simply use a capturing group:

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

See this working demo.

Edit: Read more about capturing groups here.

theftprevention
  • 5,083
  • 3
  • 18
  • 31
1

const input  = "Javascript vaja";
const output = input.replace(/ja/gi, '<b>$&</b>');

console.log(output); // <b>Ja</b>vascript va<b>ja</b>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313