小兔网

方法:1、用“substring(Math.max(this.search(/\S/),0),this.search(/\S\s*$/)+1)”语句;2、用“replace(/^\s+/,'').replace(/\s+$/,'')”语句。

javascript怎么去除字符串首尾空格-js教程

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑

javascript 去除字符串首尾空格

1、substring()截取从第一个非空格字符的索引到最后一个非空格字符索引之间的所有字符,返回截取后的字符串

String.prototype.trimOne = function () {    return this.substring(Math.max(this.search(/\S/), 0), this.search(/\S\s*$/)+1)};

2、 replace()方法,将字符串开头的所有空格用一个空字符串代替,再将字符床尾部的所有空格用一个空字符串替代

String.prototype.trimTwo = function () {  return this.replace(/^\s+/, '').replace(/\s+$/, '');};

改良简化一下,看起来更加优雅的写法

String.prototype.trimThree = function () {    return this.replace(/^\s+|\s+$/g, '')};

【相关推荐:javascript学习教程

以上就是javascript怎么去除字符串首尾空格的知识。速戳>>知识兔学习精品课!