How to replace words in text, if they belong to ar

2019-08-24 14:17发布

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!

2条回答
爷的心禁止访问
2楼-- · 2019-08-24 14:56

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.

let a: string = 'I like orange, blue, black, pink, rose, yellow, white, black'

const b: 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.

查看更多
Melony?
3楼-- · 2019-08-24 14:57

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(new RegExp(b.join('|'), 'g'), 'violet');

console.log(a);

With input

function change() {
    document.getElementById('output').innerHTML = 
        a.replace(new RegExp(b.join('|'), 'g'), document.getElementById('input').value);
}

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

查看更多
登录 后发表回答