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>