如何替换文本中的单词,如果它们属于带有 Javascript replace() 的数组 [英] How to replace words in text, if they belong to array with Javascript replace()

查看:48
本文介绍了如何替换文本中的单词,如果它们属于带有 Javascript replace() 的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的文字

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

还有一个字符串

const b: string =['black', 'yellow'];

我想将字符串 a 中的所有黑色和黄色替换为紫色,因此它必须在屏幕上看起来像

I want to replace in string a all black and yellow to violet, so it must look like on the screen

'我喜欢橙色、蓝色、紫色、粉色、玫瑰色、紫色、白色、紫色'.

我知道函数 replace(),但不知道如何将 b 作为参数传递......你能帮我吗?

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!

推荐答案

您可以使用给定数组的正则表达式,通过管道连接作为正则表达式中的 OR 符号.

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);

带输入

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>

这篇关于如何替换文本中的单词,如果它们属于带有 Javascript replace() 的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆