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 !=
  • 相关阅读:
    开源程序postGIS为postgresql提供存储空间地理数据的支持
    oracle官方文档
    postgresql转换符
    【转】oracle的Interval类型详解
    [转]千万不要把灯泡放进嘴里
    服务器运维指令
    莫名其妙的时区问题
    Linux内存思想
    oracle提高查询效率24法
    哈佛大学图书馆凌晨4点的景象
  • 原文地址:https://www.cnblogs.com/yingtoumao/p/11520446.html
Copyright © 2011-2022 走看看