从字符串中删除回车符和空格

Gue*_*est 21 javascript regex space carriage-return

我想从字符串中删除回车符和空格例如:

var t ="     \n \n    aaa \n bbb \n ccc \n";
Run Code Online (Sandbox Code Playgroud)

我希望得到结果:

t = "aaa bbb ccc"
Run Code Online (Sandbox Code Playgroud)

我使用这个,它删除回车但我仍然有空格

t.replace(/[\n\r]/g, '');
Run Code Online (Sandbox Code Playgroud)

请有人帮助我.

And*_*wby 39

尝试:

 t.replace(/[\n\r]+/g, '');
Run Code Online (Sandbox Code Playgroud)

然后:

 t.replace(/\s{2,10}/g, ' ');
Run Code Online (Sandbox Code Playgroud)

第二个应该摆脱超过1个空间


Ulu*_*rov 22

或者你可以使用单正则表达式:

t.replace(/\s+/g, ' ')
Run Code Online (Sandbox Code Playgroud)

您还需要调用.trim()因为前导和尾随空格.所以完整的将是:

t = t.replace(/\s+/g, ' ').trim();
Run Code Online (Sandbox Code Playgroud)