去空格和空白文本

//去所有空格
  var str = " 3 2 4 43 ";
  var reg = /\s+/g;
  console.log('('+str.replace(reg,"")+')') //(32443)
//去左边空格
  方法一:
    var str = " 3 2 4 43 ";
    var reg = /^\s+/g
    console.log('('+str.replace(reg,"")+')') //(3 2 4 43 )
  方法二:
    var str=" 2 1 4,2 4 ";
    //console.log(str)
    var arr=[];
    for(var i = 0;i<str.length;i ++){ //去除开头空字符串
      if(str[i] != " "){
        var a = str.indexOf(str[i]);
        break; //找到不为空字符串的,就中断
      }
    }

    for(var j = a;j < str.length-1;j ++){
      arr.push(str[j])
    }
    console.log(arr.join(""))//2 1 4,2 4 数组转为字符串
 //去右边空格
  var str = " 3 2 4 43 ";
  var reg = /\s+$/g
  console.log('('+str.replace(reg,"")+')') /( 3 2 4 43)

//去左右俩边空格
  方法1:
    var str = " 3 2 4 43 ";
    var reg = /^\s+/;
    var reg2 = /\s+$/;
    var newStr = str.replace(reg,"");
    console.log('('+newStr.replace(reg2,"")+')') //(3 2 4 43)

  方法2:
    var str = " 3 2 4 43 ";
    var reg = /(^\s+)|(\s+$)/g;
    console.log('('+str.replace(reg,"")+')')

//去空白文本节点
  var oBox = document.getElementById("box");
  removeSpace(oBox);
  console.log(oBox.childNodes[1])
  function removeSpace(node){
    for(var i = 0;i < node.childNodes.length;i ++){
      if(node.childNodes[i].nodeType === 3 && /^\s+$/.test(node.childNodes[i].nodeValue)){
        node.removeChild(node.childNodes[i])
      }
    }
    return node
  }

posted @ 2017-10-11 11:38  柯岩  阅读(254)  评论(0编辑  收藏  举报