JS Method for Removing Spaces in Strings

  • 2021-07-21 05:58:32
  • OfStack

In this paper, an example is given to describe the method of removing spaces in strings by JS. Share it for your reference, as follows:

Remove all spaces from the string, not just the front and back spaces:


text = text.replace(/\s/ig,'');

Remove the front and back spaces:

Method 1:

Use trim ()


function Trim(m){
 while((m.length>0)&&(m.charAt(0)==' '))
 m  =  m.substring(1, m.length);
 while((m.length>0)&&(m.charAt(m.length-1)==' '))
 m = m.substring(0, m.length-1);
 return m;
}

Method 2:


text = text.replace(/(^\s*)|(\s*$)/g,'');
//Recon  The train of thought: 
//-------------
// Remove the space to the left of the string 
function lTrim(str)
{
if (str.charAt(0) == " ")
{
// If the left-hand order of the string 1 Characters are empty   Lattice 
str = str.slice(1);// Remove spaces from strings 
// This 1 The sentence can also be changed to  str = str.substring(1, str.length);
str = lTrim(str); // Recursive invocation 
}
return str;
}
// Remove the space to the right of the string 
function rTrim(str)
{
var iLength;
iLength = str.length;
if (str.charAt(iLength - 1) == " ")
{
//  If the right-hand order of the string 1 Characters are spaces 
str = str.slice(0, iLength - 1);// Remove spaces from strings 
// This 1 Sentence   It can also be changed to  str = str.substring(0, iLength - 1);
str = rTrim(str); // Recursive invocation 
}
return str;
}
// Remove the spaces on both sides of the string 
function trim(str)
{
return lTrim(rTrim(str));
}

More readers interested in JavaScript can check out the topics of this site: "JavaScript Regular Expression Skills Encyclopedia", "JavaScript Replacement Operation Skills Summary", "JavaScript Search Algorithm Skills Summary", "JavaScript Data Structure and Algorithm Skills Summary", "JavaScript Traversal Algorithm and Skills Summary", "json Operation Skills Summary in JavaScript", "JavaScript Error and Debugging Skills Summary" and "JavaScript Mathematical Operation Usage Summary"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: