javascript去除字符串左右两端的空格
去除字符串左右两端的空格,在vbscript里面可以轻松地使用trim、ltrim或rtrim,但在js中却没有这3个内置方法,需要手工编写。下面的实现方法是用到了正则表达式,效率不错,并把这三个方法加入String对象的内置方法中去。
写成类的方法格式如下:(str.trim();)
<scriptlanguage="javascript">
String.prototype.trim=function(){
returnthis.replace(/(^\s*)|(\s*$)/g,"");
}
String.prototype.ltrim=function(){
returnthis.replace(/(^\s*)/g,"");
}
String.prototype.rtrim=function(){
returnthis.replace(/(\s*$)/g,"");
}
</script>
写成函数可以这样:(trim(str))
<scripttype="text/javascript">
functiontrim(str){//删除左右两端的空格
returnstr.replace(/(^\s*)|(\s*$)/g,"");
}
functionltrim(str){//删除左边的空格
returnstr.replace(/(^\s*)/g,"");
}
functionrtrim(str){//删除右边的空格
returnstr.replace(/(\s*$)/g,"");
}
</script>
以上就是2种javascript去除字符串两边空格的方法,希望大家能够喜欢。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短