Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery regex global instance or occurrences counter

I want to replace all the occurrences of a string in a string. I’m using regex with global to replace the text but need to add the occurrence number to each find.

input_value = "The [TRUCK] is green. Look at the [TRUCK]. It is a shiny [TRUCK].";

out_value = input_value.replace(/\[(TRUCK)\]/g, '<span id="id_" name="name_" class="big_truck">Big Truck</span>');

The above works but I need the ID/NAME of the SPAN tag to change for all occurrences like the following

1st
<span id="id_1" name="name_1" class="big_truck">Big Truck</span>
2nd
<span id="id_2" name="name_2" class="big_truck">Big Truck</span>
3rd
<span id="id_3" name="name_3" class="big_truck">Big Truck</span>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do something like this:

var number = 0;
var out_value = input_value.replace(/\[(TRUCK)\]/g, function() {
          let num = ++number;
          return '<span id="id_' + num + '" name="name_' + num + '" class="big_truck">Big Truck</span>';
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading