Implementation Method of removing spaces before and after strings in js, and implementation of spaces in js strings
When we edit some pages, spaces before and after 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<str.length;i++){ if(str.charAt(i)!=" ") break; } str = str.substring(i,str.length); return str; }
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.
Articles you may be interested in:
- Js trim function de-space function and regular expression collection
- Best practices for JS trim space Removal
- The javascript text box cannot be entered with Space Verification Method
- Js/jquery remove spaces, press enter, and wrap the sample code
- Js removes spaces from the string (implementation code)
- Js removes the regular expression of the first space
- Simple Example of JS removing spaces at both ends of a string
- Js removes all spaces in the input box and disables spaces.
- Use JS to replace spaces in strings