Javascript 如何用 RegExp 替换字符串

标签 javascript regex replace match

我有这个字符串

"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/

相关文章:

javascript - 一起使用 jQuery 和标准 JavaScript

javascript - 如何使用javascript获取asp.net中gridview中下拉列表的选定值?

python re.X vs automagic 行延续

php - preg_replace 导致美元符号被删除

javascript - 如何搜索和替换 {{ :example}} 中的内容

javascript - 使用 JSON 对象数据填充 html 表

javascript - 如何将单元格颜色设置为具有动态列的网格?

javascript 正则表达式 匹配 ^[^#]?

java - 在 Java 或 ANT 下以正则表达式输出换行符

Javascript 用单个正斜杠替换反斜杠和正斜杠的组合