js trim函数去空格函数与正则集锦

但是如果项目没有用到jQuery等框架的话,js本身又没有这样的函数,我们不得不自己写这样的函数,下面是函数的具体实现:

 1 //供使用者调用 
 2 function trim(s){ 
 3 return trimRight(trimLeft(s)); 
 4 } 
 5 //去掉左边的空白 
 6 function trimLeft(s){ 
 7 if(s == null) { 
 8 return ""; 
 9 } 
10 var whitespace = new String(" \t\n\r"); 
11 var str = new String(s); 
12 if (whitespace.indexOf(str.charAt(0)) != -1) { 
13 var j=0, i = str.length; 
14 while (j < i && whitespace.indexOf(str.charAt(j)) != -1){ 
15 j++; 
16 } 
17 str = str.substring(j, i); 
18 } 
19 return str; 
20 } 
21 //去掉右边的空白 
22 function trimRight(s){ 
23 if(s == null) return ""; 
24 var whitespace = new String(" \t\n\r"); 
25 var str = new String(s); 
26 if (whitespace.indexOf(str.charAt(str.length-1)) != -1){ 
27 var i = str.length - 1; 
28 while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){ 
29 i--; 
30 } 
31 str = str.substring(0, i+1); 
32 } 
33 return str; 
34 }

使用时只需调用trim函数即可。
下面是用正则的实现方法:

 1 <SCRIPT LANGUAGE="JavaScript"> 
 2 <!-- 
 3 String.prototype.Trim = function() 
 4 { 
 5     return this.replace(/(^\s*)|(\s*$)/g, ""); 
 6 } 
 7 String.prototype.LTrim = function() 
 8 { 
 9     return this.replace(/(^\s*)/g, ""); 
10 } 
11 String.prototype.RTrim = function() 
12 { 
13     return this.replace(/(\s*$)/g, ""); 
14 } 
15 //--> 
16 </SCRIPT> 
17 <input type="text" value=" 前后都是空格 " id="space"> 
18 <input type="button" value="去前后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.Trim();document.getElementById('space').select();"> 
19 <input type="button" value="去前空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.LTrim();document.getElementById('space').select();"> 
20 <input type="button" value="去后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.RTrim();document.getElementById('space').select();"> 
21 <input type="button" value="还原" onclick="javascript:document.getElementById('space').value=' 前后都是空格 ';">
原文地址:https://www.cnblogs.com/xiaoyunxiao/p/2431554.html