zoukankan      html  css  js  c++  java
  • 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 !=
  • 相关阅读:
    vue项目接入百度地图
    angularJS 十六进制与字符串相互转换
    angular项目实现mqtt的订阅与发布 ngx-mqtt
    消息中间件MQTT
    Zigbee 与 WiFi 的区别
    angular6 路由拼接查询参数如 ?id=1 并获取url参数
    SpringBoot拦截器
    SpringBoot定时任务
    SpringBoot 各层之间的关系
    百度离线地图 —— 瓦片地图下载
  • 原文地址:https://www.cnblogs.com/yingtoumao/p/11520446.html
Copyright © 2011-2022 走看看