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

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

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


当前回答

最简单的解决方案是:

let str = '\t\n\r this  \n \t   \r  is \r a   \n test \t  \r \n';
str = str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"

.replace() with /\s+/g regexp将整个字符串中的所有空白字符组更改为单个空格,然后使用.trim()结果删除文本前后所有超出的空白。

被认为是空白字符: [\f\n\r\t\v \u00a0\u1680 \u2000 -\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

其他回答

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

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

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

yourString.trim()

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

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'

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/

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

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

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

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

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

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

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

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