Home  >  Article  >  Web Front-end  >  javascript trim space removal function implementation code

javascript trim space removal function implementation code

不言
不言Original
2018-05-04 15:32:421803browse

This article mainly introduces the implementation code of the javascript trim space removal function. It has a certain reference value. Now I share it with you. Friends in need can refer to it

Remove the spaces at both ends of the string. You can easily use trim, ltrim or rtrim in vbscript, but there are no these three built-in methods in js and you need to write them manually. The following implementation method uses regular expressions, which is very efficient, and adds these three methods to the built-in methods of the String object.

<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 to select all Note: If you need to introduce external Js, you need to refresh it before executing]


Write as a function It can be like this:

Copy code The code is as follows:

<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>


The above is the detailed content of javascript trim space removal function implementation code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn