方法:1、用“substring(Math.max(this.search(/S/),0),this.search(/Ss*$/)+1)”語(yǔ)句;2、用“replace(/^s+/,'').replace(/s+$/,'')”語(yǔ)句。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦
javascript 去除字符串首尾空格
1、substring()截取從第一個(gè)非空格字符的索引到最后一個(gè)非空格字符索引之間的所有字符,返回截取后的字符串
String.prototype.trimOne = function () { return this.substring(Math.max(this.search(/S/), 0), this.search(/Ss*$/)+1) };
2、 replace()方法,將字符串開(kāi)頭的所有空格用一個(gè)空字符串代替,再將字符床尾部的所有空格用一個(gè)空字符串替代
String.prototype.trimTwo = function () { return this.replace(/^s+/, '').replace(/s+$/, ''); };
改良簡(jiǎn)化一下,看起來(lái)更加優(yōu)雅的寫法
String.prototype.trimThree = function () { return this.replace(/^s+|s+$/g, '') };
【