【问题标题】:Javascript how to replace string with RegExpJavascript如何用RegExp替换字符串
【发布时间】:2019-02-22 19:16:54
【问题描述】:

我有这个字符串

"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 制作它,请帮助

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: javascript regex replace match


【解决方案1】:

使用/\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);

【讨论】:

  • 这也为orange 添加了一个锚点
【解决方案2】:

您可以像这样对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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
相关资源
最近更新 更多