js to the string before and after the space implementation method

  • 2021-01-14 05:38:56
  • OfStack

When we do some page editing, the space before and after the string is usually not valid. So you need to filter the information when you get it.

Such as:

Enter: [space][space]a b[space][space]

Get: a[space]b

The code is as follows:
Remove the Spaces in front


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 Spaces after it


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; 
}

Method of use


function Trim(str){ 
   return LTrim(RTrim(str)); 
 }

Use a regular approach


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 1 some other methods:

Type 1: Loop check replacement


// For the user to invoke  
function trim(s){ 
return trimRight(trimLeft(s)); 
} 
// Remove the white space on the left  
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 right margin  www.ofstack.com 
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 type: cropping string mode


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 js to string before and after the space of a variety of methods, I hope to help you learn.


Related articles: