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

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

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


当前回答

var str = "bar\r\nbaz\nfoo";

str.replace(/[\r\n]/g, '');

>> "barbazfoo"

其他回答

要删除新的行字符,使用以下命令:

yourString.replace(/\r?\n?/g, '')

然后你可以删除字符串的前导和尾随空格:

yourString.trim()

我正在添加我的答案,这只是上面的一个插件, 对于我来说,我尝试了所有的/n选项,但它不起作用,我看到我的文本来自服务器,用双斜杠,所以我用了这个:

var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');

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

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(输出)

“书”

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

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

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

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

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'