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

现在我想从我的文本中删除所有的换行符(当你按Enter时产生的字符)现在使用正则表达式替换,但我如何在正则表达式中指示换行符?

如果不可能,还有别的办法吗?


当前回答

试试下面的代码。它适用于所有平台。

var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';

break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'

其他回答

方式1:

const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else

const newStringWithoutLineBreaks = yourString.replace(/(\r\n|\n|\r)/gm, "");

方式2:

const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else

const newStringWithoutLineBreaks = yourString.split('\n').join('');

这将用空格替换换行符。

someText = someText.replace(/(\r\n|\n|\r)/gm,"");

阅读这篇文章。

如果你想删除所有的控制字符,包括CR和LF,你可以使用这个:

myString.replace(/[^\x20-\x7E]/gmi, "")

它将删除所有不可打印的字符。这些字符都不在ASCII十六进制空间0x20-0x7E内。请根据需要随意修改HEX范围。

这将删除你所有的换行,空格,不必要的字符

n n n n n n n n n n n n n n n n n n n n n n n n n console.log (str) var output = str.replace(/\n|\r|\W/g, ""); console.log(输出)

“书”

我经常在jsons中的(html)字符串中使用这个正则表达式:

替换(/[\n\r\t\s]+/g, ' ')

字符串来自CMS或i18n php的html编辑器。常见的场景有:

- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
  ipsum
- lorem   ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r

正则表达式避免了这些丑陋的事情:

lorem\nipsum    => loremipsum
lorem,\nipsum   => lorem,ipsum
lorem,\n\nipsum => lorem,  ipsum
...

当然不是所有的用例,也不是最快的用例,但对于大多数文本区域和网站或web应用程序的文本来说已经足够了。