JavaScript如何自定義trim方法
更新時間:2015年07月28日 10:06:42 作者:孤月2012
本文介紹了如何自定義trim方法,trim的作用就是去除字符串前后空格,這個方法在字符串處理方面很有實(shí)用價值,需要的朋友可以參考下
相比vbscript,javascript在字符串處理方面已經(jīng)很強(qiáng)大了,但是偏偏缺少去除字符串前后空格的trim方法。
//clear the right and left space
function trim(s){
return trimRight(trimLeft(s));
}
//clear the left space
function trimLeft(s){
if(s == null) {
return "";
}
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(0)) != -1) {
var j=0, i = str.length;
while (j < i && whitespace.indexOf(str.charAt(j)) != -1){
j++;
}
str = str.substring(j, i);
}
return str;
}
//clear the right space
function trimRight(s){
if(s == null) return "";
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
var i = str.length - 1;
while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
i--;
}
str = str.substring(0, i+1);
}
return str;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
Javascript設(shè)計模式理論與編程實(shí)戰(zhàn)之簡單工廠模式
簡單工廠模式是由一個方法來決定到底要創(chuàng)建哪個類的實(shí)例, 而這些實(shí)例經(jīng)常都擁有相同的接口. 這種模式主要用在所實(shí)例化的類型在編譯期并不能確定, 而是在執(zhí)行期決定的情況。 說的通俗點(diǎn),就像公司茶水間的飲料機(jī),要咖啡還是牛奶取決于你按哪個按鈕2015-11-11
JavaScript中三個等號和兩個等號的區(qū)別(== 和 ===)淺析
javascript中比較運(yùn)算符'=='與'==='可能大家用的比較多,但是大家對他的區(qū)別不是很清楚,接下來小編給大家介紹下js中三個等號和兩個等號的區(qū)別(== 和 ===),感興趣的朋友可以參考下2016-09-09

