When we do some page editing, the spaces before and after the string are usually invalid. Therefore, filtering is required when obtaining information.
For example:
Enter : [space][space]a[space]b[space][space][space]
gets: a[space]b
The code is as follows:
Remove leading spaces
function LTrim(str){ var i; for(i=0;i<str.length;i++){ if(str.charAt(i)!=" ") break; } str = str.substring(i,str.length); return str; }
Remove the following spaces
function RTrim(str){ var i; for(i=str.length-1;i>=0;i--){ if(str.charAt(i)!=" ") break; } str = str.substring(0,i+1); return str; }
How to use
function Trim(str){ return LTrim(RTrim(str)); }
【Recommended】Use the regular method
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, ""); }
Added some other methods:
The first type: loop check and replace
//供使用者调用 function trim(s){ return trimRight(trimLeft(s)); } //去掉左边的空白 function trimLeft(s){ if(s == null) { return ""; } var whitespace = new String(" \t\n\r"); var str = new String(s); if (whitespace.indexOf(str.charAt(0)) != -1) { var j=0, i = str.length; while (j < i && whitespace.indexOf(str.charAt(j)) != -1){ j++; } str = str.substring(j, i); } return str; } //去掉右边的空白 www.jb51.net function trimRight(s){ if(s == null) return ""; var whitespace = new String(" \t\n\r"); var str = new String(s); if (whitespace.indexOf(str.charAt(str.length-1)) != -1){ var i = str.length - 1; while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){ i--; } str = str.substring(0, i+1); } return str; }
The second method: cutting strings
function trim(str){ str = str.replace(/^(\s|\u00A0)+/,''); for(var i=str.length-1; i>=0; i--){ if(/\S/.test(str.charAt(i))){ str = str.substring(0, i+1); break; } } return str; }
The above are various ways to remove spaces before and after strings in js. I hope it will be helpful to everyone's learning.