• JS 去除字符串中空格


    JS 去除字符串中空格

    去掉字符串中的所有空格,不仅仅包含前后空格:
    text   =   text.replace(/\s/ig,'');

    去掉前后空格:
    第一种方法:
    使用trim()
     function   Trim(m){  
      while((m.length>0)&&(m.charAt(0)==' '))  
      m   =   m.substring(1, m.length);  
      while((m.length>0)&&(m.charAt(m.length-1)==' '))  
      m = m.substring(0, m.length-1);  
      return m;  
      }

    第二种方法:

    text   =   text.replace(/(^\s*)|(\s*$)/g,'');

    //Recon 的思路:
    //-------------
    //去掉字串左边的空格
    function lTrim(str)
    {
    if (str.charAt(0) == " ")
    {
    //如果字串左边第一个字符为空 格
    str = str.slice(1);//将空格从字串中去掉
    //这一句也可改成 str = str.substring(1, str.length);
    str = lTrim(str); //递归调用
    }
    return str;
    }

    //去掉字串右边的空格
    function rTrim(str)
    {
    var iLength;

    iLength = str.length;
    if (str.charAt(iLength - 1) == " ")
    {
    // 如果字串右边第一个字符为空格
    str = str.slice(0, iLength - 1);//将空格从字串中去掉
    //这一句 也可改成 str = str.substring(0, iLength - 1);
    str = rTrim(str); //递归调用
    }
    return str;
    }

    //去掉字串两边的空格
    function trim(str)
    {
    return lTrim(rTrim(str));
    }

  • 相关阅读:
    [leetcode] Rotate Image
    [leetcode] Jump Game II
    [leetcode] Permutations II
    [leetcode] Permutations
    [leetcode] Wildcard Matching
    [leetcode] Multiply Strings
    [leetcode] Trapping Rain Water
    [leetcode] First Missing Positive
    [leetcode] Combination Sum II
    [leetcode] Combination Sum
  • 原文地址:https://www.cnblogs.com/nianshi/p/1689144.html
Copyright © 2020-2023  润新知