Home >Web Front-end >JS Tutorial >js remove spaces instance Trim() LTrim() RTrim()_javascript tips

js remove spaces instance Trim() LTrim() RTrim()_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:04:561125browse

1. js removes spaces from strings
//Remove left spaces;
function ltrim(s)
...{

return s.replace(/(^s*)/g, "");
}
//Remove the right space;
function rtrim(s)
...{
return s.replace(/(s*$)/g, "");
}
//Remove left and right spaces;
function trim(s)...{
// s.replace(/(^s*)|(s*$)/g, "");
return rtrim(ltrim(s));

}

2. Function to remove spaces on both sides of a string
//Parameter: string passed in by mystr
//Return: string mystr
function trim(mystr){
while ((mystr.indexOf(" ")==0) && (mystr.length>1)){
mystr=mystr.substring(1,mystr.length);
}//Remove Space in front
while ((mystr.lastIndexOf(" ")==mystr.length-1)&&(mystr.length>1)){
mystr=mystr.substring(0,mystr.length-1) ;
}//Remove following spaces
if (mystr==" "){
mystr="";
}
return mystr;
}

Statement:
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