JavaScript removing spaces in the string

Remove all spaces in a string

function trim(str) {
    return str.replace(/\s*/g, '');
}
console.log('=' + trim(' Hello World ! ') + '=');   // =HelloWorld!=

 

Removing spaces to the string

function trimBothSides(str) {
    return str.replace(/^\s*|\s*$/g, '');
}
console.log('=' + trimBothSides(' Hello World!  ') + '=');  // =Hello World!=
console.log('=' + '   Hello World !   '.trim() + '=');      // =Hello World !=

 

Remove the string of spaces to the left of

function trimLeft(str) {
    return str.replace(/^\s*/, '');
}
console.log('=' + trimLeft('   Hello World!  ') + '=');     // =Hello World!  =
console.log('=' + '   Hello World !   '.trimLeft() + '=');      // =Hello World !   =

 

White spaces to the right of the string

function trimRight(str) {
    return str.replace(/\s*$/, '');
}
console.log('=' + trimRight('   Hello World!   ') + '=');   // =   Hello World!=
console.log('=' + '   Hello World !   '.trimRight() + '=');     // =   Hello World !=

 






















Guess you like

Origin www.cnblogs.com/yingtoumao/p/11520446.html