Home >Web Front-end >JS Tutorial >JS remove spaces from string
// Function: 1) Remove all spaces before and after the string
// 2) Remove all spaces in the string (including spaces in the middle, you need to set the second parameter to: g)
function Trim(str,is_global)
{
var result;
result = str.replace(/(^s+)|(s+$)/g,"");
if(is_global.toLowerCase()=="g")
result = result.replace(/s /g,"");
return result;
}
Remove all spaces in the string, not just the leading and trailing spaces:
text = text.replace(/s/ig,'');
Remove leading and trailing spaces:
The first method:
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;
}
Second method:
text = text.replace(/(^s*)|(s*$)/g,'');
//Recon Idea:
//-------------
//Remove the space on the left side of the string
function lTrim(str)
{
if (str.charAt(0) == " ")
{
//If the first character on the left side of the string is a space
str = str.slice(1);//Remove the space from the string
//This sentence can also be changed to str = str.substring(1, str.length);
str = lTrim(str); //Recursive call
}
return str;
}
//Remove the spaces on the right side of the string
function rTrim(str)
{
var iLength;
iLength = str.length;
if (str.charAt(iLength - 1) == " ")
{
//If the first character on the right side of the string is a space
str = str.slice(0, iLength - 1); //Remove spaces from the string
//This sentence can also be changed to str = str.substring(0, iLength - 1);
str = rTrim(str); //Recursive call
}
return str;
}
//Remove the spaces on both sides of the string
function trim(str)
{
return lTrim(rTrim(str));
}