这篇文章主要介绍了关于javascript trim 去空格函数实现代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
去除字符串左右两端的空格,在vbscript里面可以轻松地使用 trim、ltrim 或 rtrim,但在js中却没有这3个内置方法,需要手工编写。下面的实现方法是用到了正则表达式,效率不错,并把这三个方法加入string对象的内置方法中去。
<input type="text" name="mytxt" value=" 12345678 " />
<input type="button" name="cmd1" onclick="mytxt2.value=mytxt.value.trim()" value="去两边的空格"/>
<input type="text" name="mytxt2"/>
<input type="button" name="cmd1" onclick="mytxt3.value=mytxt.value.ltrim()" value="去左边的空格"/>
<input type="text" name="mytxt3"/>
<input type="button" name="cmd1" onclick="mytxt4.value=mytxt.value.rtrim()" value="去右边的空格"/>
<input type="text" name="mytxt4"/>
<script language="javascript">
string.prototype.trim=function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
string.prototype.ltrim=function(){
return this.replace(/(^\s*)/g,"");
}
string.prototype.rtrim=function(){
return this.replace(/(\s*$)/g,"");
}
</script>
[ctrl+a 全选 注:如需引入外部js需刷新才能执行]
写成函数可以这样:
复制代码 代码如下:
<script type="text/javascript">
function trim(str){ //删除左右两端的空格
return str.replace(/(^\s*)|(\s*$)/g, "");
}
function ltrim(str){ //删除左边的空格
return str.replace(/(^\s*)/g,"");
}
function rtrim(str){ //删除右边的空格
return str.replace(/(\s*$)/g,"");
}
</script>
以上就是javascript trim 去空格函数实现代码的详细内容。