代码之家  ›  专栏  ›  技术社区  ›  Dima Malko

如何在指定符号前添加符号?

  •  2
  • Dima Malko  · 技术社区  · 1 年前

    我有一个字符串,它还包含以下符号 '( ) |' 将来可能会更多。

    我想 add 他们面前的另一个符号。

    字符串: 'Hi, my name | nick is Dave (for friends)' 期望值: 'Hi, my name /| nick is Dave /(for friends/)'

    到目前为止我已经试过了 replace() (仅替换第一个,失败), replaceAll() (甚至根本不工作)。

    现在我有这个工作代码,但它太长了,我很想有一个 regex ,其中我指定了所有符号,我想在前面插入符号“/”。

    或任何其他缩短代码并使其更简单的解决方案。

    我的工作代码,我想改进:

    const string= 'Hi, my name | nick is Dave (for friends)'
       const firstString = string.split('|').join("/|")
       const secondString = firstString.split('(').join("/(")
       const thirdString = secondString.split(')').join("/)")
    

    结果是 thirdString = 'Hi, my name /| nick is Dave /(for friends/)'

    1 回复  |  直到 1 年前
        1
  •  2
  •   anubhava    1 年前

    我建议使用 .replace 这里而不是 .split :

    string.replace(/[|()]/g, '\\$&')
    

    在这里 [|()] 匹配字符类中的一个给定字符,并且 '\\$&' 前缀 \ 比赛前。

    代码:

    const string= 'Hi, my name | nick is Dave (for friends)';
    var repl = string.replace(/[|()]/g, '\\$&');
    
    console.log(repl);
    //=> Hi, my name \| nick is Dave \(for friends\)