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

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

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


当前回答

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

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

其他回答

简单,我们可以删除新的行使用文本。Replace (/\n/g, " ")

const text = '学生明年\n GO \n For Trip \n'; console.log("Original: ", text); Var removed_new_line = text。Replace (/\n/g, " "); console.log("New: ", removed_new_line);

Var STR = " \n this is a string \n \n \n" console.log (str); console.log (str.trim ());

String.trim()删除字符串开头和结尾的空格…包括换行。

const myString = "   \n \n\n Hey! \n I'm a string!!!         \n\n";
const trimmedString = myString.trim();

console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"

这里有一个例子:http://jsfiddle.net/BLs8u/

注意!它只修饰字符串的开头和结尾,而不修饰字符串中间的换行符或空格。

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

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

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

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

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

regex中的换行符是\n,因此您的脚本将是

var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));