
Javascript trim string whitespace, with removing left and right spaces
When dealing with characters, it is often necessary to remove the whitespace on the left of right of the characters or remove the spaces on the left and right at the same time; because javascript does not provide such function, you can only write it yourself. The following three functions use regular expressions to filter out whitespaces.
1. Javascript trim left and right spaces
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
2. Javascript left trim string
String.prototype.l_trim = function(){
return this.replace(/(^\s*)/g, "");
}
3. Javascript right trim string
String.prototype.r_trim = function(){
return this.replace(/(\s*$)/g, "");
}
Examples of use are as follows:
<html>
<head>
<title>Javascript trim string whitespace, with removing left and right spaces</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 RemoveSpace(){
var obj = document.getElementById("myname");
//Javascript trim left and right spaces
var temp = trim(obj.value);
//trim left whitespace
var l_temp = l_trim(obj.value);
//trim right whitespace
var r_temp = r_trim(obj.value);
}
</script>
</head>
<body>
<form id="form1"action="" method="post">
<div>
Name: <input type="text" id="myname" >
<input type="button" value="Submit" onclick="return RemoveSpace()" />
</div>
</form>
</body>
</html>
If you want to use javascript to remove more spaces, please see the article "Javascript remove spaces (first and last, between words, all) with regular expression".
-
Related Reading
- Javascript multidimensional array (create, add and r
- Remove text after clicking in the textbox and then d
- Javascript get referrer url(previous page url), curr
- Javascript get current url, domain from url, relativ
- Javascript convert hex to decimal, binary to hex, oc
- Javascript delay loading images to improve web page
- Remove html element javascript by their parent or cl
- Javascript split usage and examples, with splitting
- Javascript get all input elements in form and all im
- Javascript sets the element height that cannot be au
- Javascript create element(div,li,img,span) dynamical
- Javascript click child element to add onclick to par