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 !=
  • 相关阅读:
    防止软件被暴力破解
    简单分析QQ群验证
    Hash(哈希)算法科普
    C语言自学的方法
    如何防范算法求逆
    .Net程序逆向入门教程
    分享几篇VMP研究和分析的文章
    逆向工程
    PHP之MVC项目实战(三)
    PHP之MVC项目实战(二)
  • 原文地址:https://www.cnblogs.com/yingtoumao/p/11520446.html
Copyright © 2011-2022 走看看