2

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.

0

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.