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

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

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


当前回答

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

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

其他回答

我经常在jsons中的(html)字符串中使用这个正则表达式:

替换(/[\n\r\t\s]+/g, ' ')

字符串来自CMS或i18n php的html编辑器。常见的场景有:

- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
  ipsum
- lorem   ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r

正则表达式避免了这些丑陋的事情:

lorem\nipsum    => loremipsum
lorem,\nipsum   => lorem,ipsum
lorem,\n\nipsum => lorem,  ipsum
...

当然不是所有的用例,也不是最快的用例,但对于大多数文本区域和网站或web应用程序的文本来说已经足够了。

在mac上,只需在regexp中使用\n来匹配换行符。代码是字符串。Replace (/\n/g, "), ps:后面的g表示匹配所有,而不仅仅是第一个。

在窗户上,它将是\r\n。

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

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

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

yourString.trim()

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/

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

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

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