user705179
user705179

Reputation: 83

Replace regular expression matches with array of values

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

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

Use a replacer function that shifts 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

Related Questions