首页 > 编程语言 > 详细

JavaScript去除字符串中的空格

时间:2019-09-14 23:28:36      阅读:98      评论:0      收藏:0      [点我收藏+]

去除字符串中所有空格

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 !=

 

JavaScript去除字符串中的空格

原文:https://www.cnblogs.com/yingtoumao/p/11520446.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!