如何从字符串中删除所有换行符

问题描述:

我在textarea中有一个文本,我使用.value属性读出来。

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

现在我想删除所有换行符(生成的字符)现在使用.replace和正则表达式从我的文本中按 Enter ),但如何在正则表达式中指明换行?

Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?

如果那是不可能的,还有另一种方法吗?

If that is not possible, is there another way?

这可能是常见问题解答。无论如何,换行符(更好:换行符)可以是回车符(CR, \ r ,在较旧的Mac上),换行符(LF, \ n ,在Unices(包括Linux)上)或CR后跟LF( \\\\ n ,在WinDOS上)。 (与另一个答案相反,这与没有与字符编码有关。)

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.)

因此,最有效的 RegExp 匹配所有变体的文字是

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.)