![](/img/trans.png)
[英]How do I replace last part of string using string.replace() Javascript / Node.js
[英]How do I use JS String.replace and replace with a part of a bracket group using RegEx
我有这个代码:
string
.replace(/^1[xyz]/g, "$1")
.replace(/-1[xyz]/g, "-$1")
.replace(/ 1[xyz]/g, " $1");
其中string
是一个数学表达式。 我希望将$1
替换为 x、y 或 z,具体取决于它在括号中匹配的字母。 这应该替换字符串中的所有出现。 如何使其正确替换?
例子:
1x
→ x
-1x
→ -x
5x + 1y
→ 5x + y
1x - 1z
→ x - z
11x + 21y
→ 11x + 21y
(只替换1,不替换11、21等)你可能会使用
\b1([xyz])
\b1
一个词的边界,然后匹配 1([xyz])
捕获组 1,匹配x
y
或z
之一在替换使用组 1 中。
const pattern = /\b1([xyz])/g; [ "1x", "-1x", "5x + 1y", "1x - 1z", "11x + 21y" ].forEach(s => console.log(s + " => " + s.replace(pattern, "$1")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.