【问题标题】:How to replace the last character of a string matched by Regex expression (javascript) [duplicate]如何替换与正则表达式匹配的字符串的最后一个字符(javascript)[重复]
【发布时间】:2019-07-15 13:58:04
【问题描述】:

我正在尝试从包含地址的字符串创建一个数组,并且需要用分号替换逗号分隔符,因为地址包含许多逗号,arr.split 将创建不正确的条目。

我不知道如何匹配仅出现在邮政编码之后的逗号。

经过一些研究,我一直在尝试使用:str.replace(/(?<=\d{5}),/g, "; ");

(?<=y)x 表达式似乎不起作用,但我想到的所有其他方法最终都会删除 zip 和逗号,或者只是简单地没有做任何事情。 (source where I found all I know of Regex)。

【问题讨论】:

  • 也许str.replace(/(\d{5}),/g, "$1;")?

标签: javascript regex


【解决方案1】:

如果 JavaScript 引擎支持lookbehind,您的方式将起作用,该功能仅在 ES2018 中添加:

// ONLY WORKS ON ENGINES THAT SUPPORT LOOKBEHIND
const str = "Testing 90210,testing,testing, ...";
console.log(str.replace(/(?<=\d{5}),/g, "; "));

否则,在捕获组中也匹配邮政编码并使用$1 将其包含在替换中:

const str = "Testing 90210,testing,testing, ...";
console.log(str.replace(/(\d{5}),/g, "$1; "));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多