Two ways to implement the trim () function in JavaScript _javascript techniques

Source: Internet
Author: User
Tags rtrim

In JavaScript we need to use a lot of trim, but JavaScript has no independent trim function or method to use, so we need to write a trim function to achieve our goal.

Programme I:

A prototype invocation, Obj.trim (), is simple and widely used, and is defined in the following ways:

Copy Code code as follows:

<script language= "JavaScript" >
/**
* Delete the left and right sides of the space
*/
String.prototype.trim=function ()
{
Return This.replace (/(^\s*) | ( \s*$)/g, ");
}
/**
* Delete the Left space
*/
String.prototype.ltrim=function ()
{
Return This.replace (/(^\s*)/g, ");
}
/**
* Remove the space on the right
*/
String.prototype.rtrim=function ()
{
Return This.replace (/(\s*$)/g, ");
}
</script>

Use the example below:
Copy Code code as follows:

<script type= "Text/javascript" >
Alert (document.getElementById (' abc '). Value.trim ());
Alert (document.getElementById (' abc '). Value.ltrim ());
Alert (document.getElementById (' abc '). Value.rtrim ());
</script>

Programme II:

Called as a tool, that is, the form of trim (obj), which can be used for special processing needs, defined in the following ways:

Copy Code code as follows:

<script type= "Text/javascript" >
/**
* Delete the left and right sides of the space
*/
function Trim (str)
{
Return Str.replace (/(^\s*) | ( \s*$)/g, ");
}
/**
* Delete the Left space
*/
function LTrim (str)
{
Return Str.replace (/(^\s*)/g, ");
}
/**
* Remove the space on the right
*/
function RTrim (str)
{
Return Str.replace (/(\s*$)/g, ");
}
</script>

Use the example below:
Copy Code code as follows:

<script type= "Text/javascript" >
Alert (Trim (document.getElementById (' abc '). value));
Alert (LTrim document.getElementById (' abc '). Value);
Alert (RTrim document.getElementById (' abc '). Value);
</script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.