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

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

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


当前回答

换行符(最好是换行符)可以是回车符(CR, \r,在旧的mac上),换行符(LF, \n,在unix包括Linux上)或CR后面跟着LF (\r\n,在windows上)。(与另一个答案相反,这与字符编码无关。)

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

/\r?\n|\r/

如果你想匹配字符串中的所有换行符,使用全局匹配,

/\r?\n|\r/g

分别。然后按照其他几个答案中建议的替换方法进行。(可能您不希望删除换行符,而是使用其他空白符替换它们,例如空格字符,以便单词保持完整。)

其他回答

方式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('');

Const text = 'test\nwith\nline\nbreaks'

const textwithoutbreak = text.split('\n')。加入(' ')

如果碰巧你不需要这个htm字符&nbsp shile使用str.replace(/(\r\n|\n|\r)/gm, ""),你可以使用这个str.split('\n').join(");

干杯

如何找到换行符在不同的操作系统编码中是不同的。Windows是\r\n,但Linux只使用\n,而苹果使用\r。

我在JavaScript的换行符中发现了这个:

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

这应该会删除所有的换行符。

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

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'