Skip to content Skip to sidebar Skip to footer

How To Replace Words In Text, If They Belong To Array With Javascript Replace()

I have a text like const a: string = 'I like orange, blue, black, pink, rose, yellow, white, black'; And a string const b: string =['black', 'yellow']; I want to replace in stri

Solution 1:

You could use a regular expression with the given array, joined by pipe as OR sign in the regular expression.

let a = 'I like orange, blue, black, pink, rose, yellow, white, black';
const b = ['black', 'yellow'];
   
a = a.replace(newRegExp(b.join('|'), 'g'), 'violet');

console.log(a);

With input

functionchange() {
    document.getElementById('output').innerHTML = 
        a.replace(newRegExp(b.join('|'), 'g'), document.getElementById('input').value);
}

let a = 'I like orange, blue, black, pink, rose, yellow, white, black';
const b = ['black', 'yellow'];
<inputid="input"type="text"value=""onchange="change();" /><divid="output"></div>

Solution 2:

replace() doesn't accept arrays. But there is a work around. What you could do is loop over each word you would like to replace.

leta: string = 'I like orange, blue, black, pink, rose, yellow, white, black'constb: string = ['black', 'yellow']

b.forEach(word => {
    a = a.replace(word, 'violet')
})

Also, const are immutable so if you want a variable you can modify make sure to use let.

Post a Comment for "How To Replace Words In Text, If They Belong To Array With Javascript Replace()"