我有这个字符串
"red col. yellow; col. black; col. green; orange; col. white; blue col. purple;"
我需要得到黄色、黑色、绿色、白色、紫色,只是没有“col”的颜色。和 ';'并将此字符串更改为:
"red col. < a>yellow<\a> ; col. < a>black<\a> ; col. < a>green<\a>; orange; col. <a>white<\a>; blue; col. < a>purple<\a>;"
如何使用 javascript reg exp 来实现它,请帮忙
最佳答案
使用/\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);
关于Javascript 如何用 RegExp 替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833725/