Javascript如何用RegExp替换字符串

时间:2019-02-22 19:16:54

标签: javascript regex replace match

我有这个字符串

 "red col. < a>yellow<\a> ; col. < a>black<\a> ; col. < a>green<\a>; orange; col. <a>white<\a>; blue; col. < a>purple<\a>;"

我需要得到黄色,黑色,绿色,白色,紫色,只是没有'col'的颜色。和';'并将此字符串更改为此:

multiple

如何使用javascript reg exp做到这一点,请帮助

2 个答案:

答案 0 :(得分:4)

使用/\w+(?=;)/g匹配以;结尾的单词,并使用String.replace()将匹配项替换为您想要的匹配项:

const str = 'red col.  yellow;   col.  black;  col.  green; orange; col. white; blue col. purple;';

const result = str.replace(/\w+(?=;)/g, match => '<a>' + match + '</a>');

console.log(result);

对于特定颜色:

const str = 'red col.  yellow;   col.  black;  col.  green; orange; col. white; blue col. purple;';

const colors = ["yellow", "black", "green", "white", "purple"];

const exp = new RegExp(colors.join('|'), 'g');

const result = str.replace(exp, match => '<a>' + match + '</a>');

console.log(result);

答案 1 :(得分:0)

您可以像这样使用捕获组来replace :(不确定这是最有效的方法)

const str = "red col.  yellow;   col.  black;  col.  green; orange; col. white; blue col. purple;"

const newStr = str.replace(/(?<=col.)(\s+)(\w+);/g, "$1<a>$2</a>;")

console.log(newStr)