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 string a all black and yellow to violet, so it must look like on the screen
'I like orange, blue, violet, pink, rose, violet, white, violet'.
I know about function replace(), but have no idea how to pass b as argument...Could you please help me?
And if it is possible I would like to replace not with violet, but with input field, so i could type my own colors right in the text...Thank you!
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.Also,
const
are immutable so if you want a variable you can modify make sure to use let.You could use a regular expression with the given array, joined by pipe as OR sign in the regular expression.
With input