Reputation: 83
I have a regular expression to find text with ???
inside a string.
const paragraph = 'This ??? is ??? and ???. Have you seen the ????';
const regex = /(\?\?\?)/g;
const found = paragraph.match(regex);
console.log(found);
Is there a way to replace every match with a value from an array in order?
E.g. with an array of ['cat', 'cool', 'happy', 'dog']
, I want the result to be 'This cat is cool and happy. Have you seen the dog?'
.
I saw String.prototype.replace()
but that will replace every value.
Upvotes: 2
Views: 1978
Reputation: 370979
Use a replacer function that shift
s from the array of replacement strings (shift
removes and returns the item at the 0th index):
const paragraph = 'This ??? is ??? and ???. Have you seen the ????';
const regex = /(\?\?\?)/g;
const replacements = ['cat', 'cool', 'happy', 'dog'];
const found = paragraph.replace(regex, () => replacements.shift());
console.log(found);
(if there are not enough items in the array to replace all, the rest of the ???
s will be replaced by undefined
)
Upvotes: 8