Escape new lines with JS

后端 未结 3 1613
情歌与酒
情歌与酒 2021-02-13 23:49

I have a string that looks something like this:

\"Line 1\\nLine 2\"

When I call length on it, though, it\'s one character short:



        
3条回答
  •  暖寄归人
    2021-02-14 00:03

    Whenever you get Javascript to interpret this string, the '\n' will be rendered as a newline (which is a single character, hence the length.)

    To use the string as a literal backslash-n, try escaping the backslash with another one. Like so:

    "Line 1\\nLine 2"
    

    If you can't do this when the string is created, you can turn the one string into the other with this:

    "Line 1\nLine 2".replace(/\n/, "\\n");
    

    If you might have multiple occurrences of the newline, you can get them all at once by making the regex global, like this:

    "Line 1\nLine 2\nLine 3".replace(/\n/g, "\\n");
    

提交回复
热议问题