javascript replace() not replacing text containing literal \r\n strings

后端 未结 3 1768
庸人自扰
庸人自扰 2020-12-29 07:36

Using this bit of code trims out hidden characters like carriage returns and linefeeds with nothing using javascript just fine:

value = value.replace(/[\\r\\         


        
3条回答
  •  渐次进展
    2020-12-29 08:12

    If you want to match literal \r and literal \n then you should use the following:

    value = value.replace(/(?:\\[rn])+/g, "");
    

    You might think that matching literal \r and \n with [\\r\\n] is the right way to do it and it is a bit confusing but it won't work and here is why:

    Remember that in character classes, each single character represents a single letter or symbol, it doesn't represent a sequence of characters, it is just a set of characters.

    So the character class [\\r\\n] actually matches the literal characters \, r and n as separate letters and not as sequences.

    Edit: If you want to replace all carriage returns \r, newlines \n and also literal \r and '\n` then you could use:

    value = value.replace(/(?:\\[rn]|[\r\n]+)+/g, "");
    

    About (?:) it means a non-capturing group, because by default when you put something into a usual group () then it gets captured into a numbered variable that you can use elsewhere inside the regular expression itself, or latter in the matches array.

    (?:) prevents capturing the value and causes less overhead than (), for more info see this article.

提交回复
热议问题