删除字符串两侧的空格:

方法1 – trim() 函数
let text = "       Bin go!        ";
let result = text.trim();
//结果:Bin go!
方法2 – 正则表达式
let text = "       Bin go!        ";
let result = text.replace(/^\s+|\s+$/gm,'');
//结果:Bin go!

删除字符串所有的空格:

let text = "       B in     go!        ";
let result = text.replace(/\s/g, "");
//结果:Bingo!

将连续的多个空格精简到一个空格:

let text = "       B         in    go!        
Bingo!
";
let result = text.replace(/  +/g, ' ');
//结果: B in go! 
//Bingo! 

将Tab缩进,换行,多个连续空格均精简到一个空格:

let text = "       Bingo!   
Bingo!  Bingo!
     ";
let result = text.replace(/\s\s+/g, ' ');
result = result.replace(/\r?\n|\r/g,' '); // 专门去掉“换行”
//结果: Bingo! Bingo! Bingo! 

本篇文章相关标签: