JavaScript去除字符串中的空格
去除字符串中所有空格
function trim(str) { return str.replace(/\s*/g, ''); } console.log('=' + trim(' Hello World ! ') + '='); // =HelloWorld!=
去除字符串中间的空格
function trimMiddle(str) { let head = str.match(/^\s*\S*/)[0]; let end = str.match(/\S*\s*$/)[0]; let middle = str.replace(/(^\s*\S*)|(\S*\s*$)/g, '').replace(/\s*/g, ''); return head + middle + end; } console.log('=' + trimMiddle(' Hello World ! ') + '='); // = HelloWorld! =
function trimMiddle(str) { return str.match(/(^\s*)|(\S+)|(\s*$)/g).join(''); } console.log('=' + trimMiddle(' Hel l o # $ world !( ) h h ') + '='); // = Hello#$world!()hh =
去除字符串两边的空格
function trimBothSides(str) { return str.replace(/^\s*|\s*$/g, ''); } console.log('=' + trimBothSides(' Hello World! ') + '='); // =Hello World!=
console.log('=' + ' Hello World ! '.trim() + '='); // =Hello World !=
去除字符串左边的空格
function trimLeft(str) { return str.replace(/^\s*/, ''); } console.log('=' + trimLeft(' Hello World! ') + '='); // =Hello World! =
console.log('=' + ' Hello World ! '.trimLeft() + '='); // =Hello World ! =
去除字符串右边的空格
function trimRight(str) { return str.replace(/\s*$/, ''); } console.log('=' + trimRight(' Hello World! ') + '='); // = Hello World!=
console.log('=' + ' Hello World ! '.trimRight() + '='); // = Hello World !=