<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>
for example:
<input type="text" name="mytxt" value=" 12345678 " /><br>
<input type="button" name="cmd1" onclick="mytxt2.value=mytxt.value.trim()" value="去两边的空格"/>
<input type="text" name="mytxt2"/><br>
<input type="button" name="cmd1" onclick="mytxt3.value=mytxt.value.ltrim()" value="去左边的空格"/>
<input type="text" name="mytxt3"/><br>
<input type="button" name="cmd1" onclick="mytxt4.value=mytxt.value.rtrim()" value="去右边的空格"/>
<input type="text" name="mytxt4"/><br>
<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>
javascript自定义trim()函数(来源:快乐的笛子的博客)
最新推荐文章于 2023-10-26 16:28:13 发布