【问题标题】:How to prefix certain characters in a string with regex?如何使用正则表达式为字符串中的某些字符添加前缀?
【发布时间】:2023-02-03 21:20:49
【问题描述】:

假设以下,

const str = `
    hello!
    proceed - click button below.
`

我需要在某些字符前加上\\。在这种情况下,我需要以下结果:

`
    hello\\!
    proceed \\- click button below\\.
`

目前,我正在这样做:

const str = `
    hello!
    proceed - click button below.
`.replace(/!/gm, '\\!').replace(/-/gm, '\\-').replace(/\./gm, '\\.')

console.log(str);

看起来很乱。有什么更好的方法吗?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    使用捕获组。 () 组内有您要替换的字符 [!-.],然后在替换引用组 $1

    const str = `
        hello!
        proceed - click button below.
    `.replace(/([!-.])/gm, '\\$1')
    console.log(str)

    【讨论】:

    • 我怎样才能得到预期的结果?这只会在每个字符前添加一个反斜杠
    猜你喜欢
    • 1970-01-01
    • 2011-08-13
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多