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>
>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>';
});