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

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

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


当前回答

使用下面的函数,让您的生活变得简单

最简单的方法是使用正则表达式来检测和替换字符串中的换行符。在这种情况下,我们使用replace函数和要替换的字符串,在我们的情况下是一个空字符串。

function remove_linebreaks( var message ) {
    return message.replace( /[\r\n]+/gm, "" );
}

在上面的表达式中,g和m是全局和多行标记

其他回答

这将用空格替换换行符。

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

阅读这篇文章。

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

干杯

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

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'

你可以在正则表达式中用\n表示换行,用\r表示回车。

var str2 = str.replace(/\n|\r/g, "");

不同的操作系统使用不同的行尾,使用不同的\n和\r组合。这个正则表达式将全部替换。

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