主页 > 软件教程

js去空格函数及用法

软件教程 2024-01-20

在处理字符时,常常需要去掉字符左边的、右边的空格或同时去掉左边右边的空格;由于Javascript没有提供这类函数,所以只能自己写。以下三个函数均使用正则表达式过滤掉空格。

1、同时去掉左边的和右边的空格
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}

 

2、仅去掉左边的空格
String.prototype.l_trim = function(){
return this.replace(/(^\s*)/g, "");
}

 

3、仅去掉右边的空格
String.prototype.r_trim = function(){
return this.replace(/(\s*$)/g, "");
}

 

 

使用实例如下:

<html>
<head>
<title>js的去空格函数及用法</title>
<script language="JavaScript" type="text/javascript">
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.l_trim = function(){
return this.replace(/(^\s*)/g, "");
}
String.prototype.r_trim = function(){
return this.replace(/(\s*$)/g, "");
}
function clearSpace(){
var obj = document.getElementById("myname");

//去掉左右边空格
var temp = trim(obj.value);

//去掉左边空格
var l_temp = l_trim(obj.value);

//去掉右边空格
var r_temp = r_trim(obj.value);
}
</script>
</head>
<body>
<form id="form1"action="" method="post">
<div>
姓名:<input type="text" id="myname" >
<input type="button" value="提 交" onclick="return clearSpace()" />
</div>
</form>
</body>
</html>


标签: js去空格函数

电脑软硬件教程网 Copyright © 2016-2030 www.computer26.com. Some Rights Reserved.