How to remove all line breaks from a string

前端 未结 16 1290
轮回少年
轮回少年 2020-11-22 11:36

I have a text in a textarea and I read it out using the .value attribute.

Now I would like to remove all linebreaks (the character that is produced when you press

16条回答
  •  名媛妹妹
    2020-11-22 12:14

    This is probably a FAQ. Anyhow, line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)

    Therefore, the most efficient RegExp literal to match all variants is

    /\r?\n|\r/
    

    If you want to match all newlines in a string, use a global match,

    /\r?\n|\r/g
    

    respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)

提交回复
热议问题