【发布时间】:2019-03-09 20:31:38
【问题描述】:
我正在尝试使用正则表达式概念将 2% 替换为 ''(empty)。如果输入字符串是 % 或 2%,则应将其替换为 ''(empty):
const str = "2%";
console.log(`2%`.replace(/^\d%$|\d(?=%)/, ''));
console.log(`2%`.replace(/\d(?=%)|^\d%$/, ''));
(a|b) Matches the a or the b part of the subexpression.
"2%".replace(/^\d%$|\d(?=%)/, '')。这很好用。
但是,"2%".replace(/\d(?=%)|^\d%$/, '') 没有。
【问题讨论】:
-
那么您的问题和问题是什么?您似乎有有效的源代码....
-
|的左侧匹配,所以这就是替换的内容。到底有什么令人惊讶的地方? -
@Pointy,它像短路运算符一样工作吗?
-
是的,第一个匹配“wins”的选项。
标签: javascript regex