gpt4 book ai didi

javascript - 正则表达式替换为组加上javascript中的可选组

转载 作者:行者123 更新时间:2023-12-01 01:32:14 25 4
gpt4 key购买 nike

What's working: I'm using a regex similar to the one below for phone numbers (the actual regex is here) that can grab extensions as an optional 4th group. The regex itself is working fine for the first three groups as shown below

"555-555-5555 x214".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3");
// returns 555-555-5555

What I'm looking for: I can't find the syntax for the replace string to insert the phone extension preceded by a x ONLY if the 4th group is captured. In my real regex, the phone extension could be marked by few different character designations which I would like to simply replace with an "x".

如果我使用:

"555-555-5555 x214".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3 x4");
// returns 555-555-5555 x214

"555-555-5555".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3 x4");
// will return 555-555-5555 x

在最后一个示例中,我得到了“x”(对此我并不感到惊讶),因此我正在寻找仅在捕获到某些内容时才添加“x”加组 4 的语法。

这可以用 String.replace 实现吗?如果没有,一旦我确定了它们的部分,是否有更有效的方法可以用格式化的数字类型替换这些组?

最佳答案

String#replace 函数还可以将函数作为第二个参数,这比字符串更具表现力。

例如:

"555-555-5555".replace(/(\d{3})-(\d{3})-(\d{4})(?: +x(\d+))?/, replacer);

function replacer(match, p1, p2, p3, p4, offset, string) {
return `${p1}-${p2}-${p3}` + (p4 ? ` x${p4}` : '')
}

参见MDN documentation了解更多详情:)

请注意,您的正则表达式需要一些修改。在这里玩一下:https://regex101.com/r/rtJYTw/1

关于javascript - 正则表达式替换为组加上javascript中的可选组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53162139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com