今天遇到了以关于JavaScript 中怎么去掉 字符串中前后两段的空格 ,我只好向就得js中也后Trim() 函数,后来试试了不
行,就网上找了下解决方法,其中用到了正则表达式 ,整理了下:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>测试去空格-柯乐义</title> 6 <script type="text/javascript"> 7 //http://www.cnblogs.com/roucheng/ 8 //Trim() , Ltrim() , RTrim() 函数 9 String.prototype.Trim = function() 10 { 11 return this.replace(/(^s*)|(s*$)/g, ''); 12 } 13 14 String.prototype.LTrim = function() 15 { 16 return this.replace(/(^s*)/g, ""); 17 } 18 19 String.prototype.RTrim = function() 20 { 21 return this.replace(/(s*$)/g, ""); 22 } 23 24 function testTrim() 25 { 26 var name; 27 name = document.keleyiform.uname.value.Trim(); 28 //name = document.keleyiform.uname.value.RTrim(); 29 //name = document.keleyiform.uname.value.LTrim(); 30 if (name.length == 0) { 31 alert("用户明不能为空!" + name.length); 32 document.myform.