方法: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学习教程】
立即学习“Java免费学习笔记(深入)”;
以上就是javascript怎么去除字符串首尾空格的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号