Home > Web Front-end > JS Tutorial > Several methods to remove spaces on the left and right sides of strings in js_javascript skills

Several methods to remove spaces on the left and right sides of strings in js_javascript skills

WBOY
Release: 2016-05-16 19:22:22
Original
1120 people have browsed it

//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 character Remove
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 spaces on both sides of the string
function trim(str)
{
return ltrim(rtrim(str)) ;
}

//Rainy Day 5337’s idea:
//----------------
function alltrim(a_strvarcontent)
{
var pos1, pos2, newstring;

pos1 = 0;
pos2 = 0;
newstring = ""

if (a_strvarcontent.length > 0)
{
for( i=0; i //recon: This sentence should be wrong and should be changed to:
//for( i=0; i {
if (a_strvarcontent.charat(i) == " " )
pos1 = pos1 1;
else
break;
}

for( i=a_strvarcontent.length; i>=0 ; i--)
//recon: This sentence should be wrong and should be changed to:
//for( i=a_strvarcontent.length -1; i>=0 ; i--)
{
if ( a_strvarcontent.charat(i) == " " )
pos2 = pos2 1;
else
break;
}

newstring = a_strvarcontent.substring(pos1, a_strvarcontent.length-pos2)

}

return newstring;

}

//hooke’s idea:
//-------------
function jtrim(sstr)
{
var astr="";
var dstr="";
var flag=0;
for (i=0;i {if ((sstr.charat(i)!=' ')| |(flag!=0))
{dstr =sstr.charat(i);
flag=1;
}
}
flag=0;
for (i= dstr.length-1;i>=0;i--)
{if ((dstr.charat(i)!=' ')||(flag!=0))
{astr =dstr. charat(i);
flag=1;
}
}
dstr="";
for (i=astr.length-1;i>=0;i--) dstr =astr.charat(i);
return dstr;
}
Why not use regular expressions?
String.prototype.Trim = function()
{
return this.replace(/(^s*)|(s*$)/g, "");
}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template