How to replace words in text, if they belong to array with Javascript replace()

老子叫甜甜 提交于 2020-01-07 03:52:09

问题


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!


回答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(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>



回答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.

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.



来源:https://stackoverflow.com/questions/44525462/how-to-replace-words-in-text-if-they-belong-to-array-with-javascript-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!