JS基础回顾,小练习(去除字符串空格)

方法1:

var str = ' h t m l 5 '; function trim(str) { var reg = /(\s+)/g; var m,s = str; while(m = reg.exec(s)){ s = s.replace(m[1],""); } return s; } str = trim(str); console.log(str); //html5

方法2:

var str = '  h    t m l   5  c s  s 3'; function trim(str){ for(var i=0,s = str;i<str.length;i++){ s = s.replace(" ",""); } return s; } console.log(trim(str)); //html5css3

方法3:

var str = '  h    t m l   5  c s  s 3'; function trim(str){ var s = ''; var reg = /[^\s]/g; var m; while(m = reg.exec(str)){ s += m; } return s; } console.log(trim(str)); //html5css3

 

你可能感兴趣的:(JS基础回顾,小练习(去除字符串空格))