javascript去除空格的方法:1、利用replace()函數(shù)和正則表達(dá)式,例“str.replace(/s+/g,"")”語(yǔ)句可以去除所有空格;2、利用trim()函數(shù),可以去除字符串兩端的空白字符,語(yǔ)法“$.trim(str)”。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
方法1:使用replace()函數(shù)配合正則表達(dá)式
replace()方法用于在字符串中用一些字符替換另一些字符,或替換一個(gè)與正則表達(dá)式匹配的子串。
下面我們來(lái)具體看看:
去除所有空格:
str=str.replace(/s+/g,"");
去除兩頭空格:
str=str.replace(/^s+|s+$/g,"");
去除左空格:
str=str.replace( /^s*/g, '');
去除右空格:
str=str.replace(/(s*$)/g, "");
方法2:借助jQuery的trim()函數(shù)
$.trim() 函數(shù)用于去除字符串兩端的空白字符。
注意:$.trim()函數(shù)會(huì)移除字符串開(kāi)始和末尾處的所有換行符,空格(包括連續(xù)的空格)和制表符。如果這些空白字符在字符串中間時(shí),它們將被保留,不會(huì)被移除。
示例:
$(function () { var str = " lots of spaces before and after "; $( "#original" ).html( "Original String: '" + str + "'" ); $( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" ); })
輸出結(jié)果
Original String: ' lots of spaces before and after ' $.trim()'ed: 'lots of spaces before and after'
【推薦學(xué)習(xí):javascript高級(jí)教程】