This article mainly introduces the implementation method of removing spaces before and after strings in js, and focuses on the use of regular expressions. If you are interested, please refer to when we edit some pages, the leading and trailing spaces of the string are usually invalid. Therefore, you must filter the information.
For example:
Input: [Space] [space] a [space] B [space] [space] [space]
Get: A [space] B
The Code is as follows:
Remove leading space
Function LTrim (str) {var I; for (I = 0; I
Remove 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; }
Usage
function Trim(str){ return LTrim(RTrim(str)); }
[Recommended] Regular Expression
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, ""); }
Add other methods:
First: Replacement of cyclic check
// For the user to call function trim (s) {return trimRight (trimLeft (s);} // remove the left blank 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 ;}// remove the white space on the right. 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 ;}
Method 2: Crop a string
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 is a variety of methods for js to remove spaces before and after strings. I hope this will be helpful for your learning.