Home > Web Front-end > JS Tutorial > JavaScript custom methods implement the functions of trim(), Ltrim(), and Rtrim()_javascript skills

JavaScript custom methods implement the functions of trim(), Ltrim(), and Rtrim()_javascript skills

WBOY
Release: 2016-05-16 17:18:01
Original
1289 people have browsed it

Removing spaces at both ends of a string is a very common method for string processing. Unfortunately, JavaScript does not have these three methods, only we have customized them:
Step 1, add members to String

Copy code The code is as follows:

String.prototype.Trim = function(){ return Trim(this);}
String.prototype.LTrim = function(){return LTrim(this);}
String.prototype.RTrim = function(){return RTrim(this);}

Second Step, implement the method
Copy code The code is as follows:

function LTrim(str)
{
var i;
for(i=0;i{
if(str.charAt(i)!=" "&&str.charAt(i)! =" ")break;
}
str=str.substring(i,str.length);
return str;
}
function RTrim(str)
{
var i;
for(i=str.length-1;i>=0;i--)
{
if(str.charAt(i)!=" "&&str.charAt(i )!=" ")break;
}
str=str.substring(0,i 1);
return str;
}
function Trim(str)
{
return LTrim(RTrim(str));
}

Of course, you can also use regular expressions, so that the code is clearer and more efficient,
Copy code The code is as follows:

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, "");
}
Related labels:
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