How to globally replace pipe symbol “|” in string

前端 未结 5 1355
北恋
北恋 2020-12-06 05:25

How can I globally replace the | (pipe) symbol in a string? When I try to replace it with \"so|me|str|ing\".replace(/|/g, \'-\'), I get \"-s-

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 05:57

    In my case, the pipe was coming as an variable, so I couldn't use any of these solutions. Instead, You can use:

    let output_delimiter  ='|';
    let str= 'Foo|bar| Test';
    
    str.replace(new RegExp('[' + output_delimiter + ']', 'g'), '-')
    
    //should be 'Foo-bar- Test'
    

提交回复
热议问题