找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 查看内容

javascript怎么去除字符串首尾空格

作者:模板之家 2021-6-15 20:51 113人关注

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

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

本教程操作环境: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怎么去除字符串首尾空格的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章!


路过

雷人

握手

鲜花

鸡蛋
来自: 网络收集

全部回复(0)