How to globally replace pipe symbol “|” in string

前端 未结 5 1348
北恋
北恋 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 06:06

    Another solution is, to do a substring replacement instead of a regex to replace the pipe character. However, the String.prototype.replace() method will only replace the first substring instance, like here:

    "so|me|str|ing".replace("|", "-"); // "so-me|str|ing" → WRONG
    

    Possible workarounds:

    1. Split the string into an array and join it with the new delimiter:
    "so|me|str|ing".split("|").join("-"); // "so-me-str-ing" → RIGHT
    
    1. Use a loop to replace one substring after the other.
    var str = "so|me|str|ing"; 
    while(str.indexOf("|") >= 0) {
      str = str.replace("|", "-"); // "so-me|str|ing" → RIGHT
    }
    

    Use .replaceAll()

    Use the modern approach String.prototype.replaceAll() -- beware, that this method is only supported by a few browsers yet:

    "so|me|str|ing".replaceAll("|", "-"); // "so-me-str-ing" → RIGHT
    

提交回复
热议问题