18

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.

2
  • Why not just execute two case-sensitive replace() calls?
    – fred02138
    Oct 3, 2013 at 14:32
  • i am not pretty sure what your solution is but i want to handle cases like : Bavascript vaba => <b>B</b>avascript va<b>b</b>a and replacing iteratively will crete problems in this case. Oct 3, 2013 at 14:38

2 Answers 2

25

Simply use a capturing group:

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

See this working demo.

Edit: Read more about capturing groups here.

1
  • 1
    perfecttttt.. thanks a lot . works like charm.(i can only accept answer after 5 minutes SO says so :)) Oct 3, 2013 at 14:39
2

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

console.log(output); // <b>Ja</b>vascript va<b>ja</b>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.