There are many places in JavaScript that we need to use trim, but JavaScript does not have independent trim functions or methods to use, so we need to write a trim function ourselves to achieve our purpose.
Plan 1:
Called in prototype form, i.e. obj.trim(), this method is simple and widely used, and the definition is as follows:
The code copy is as follows:
<script language=”javascript”>
/**
* Delete spaces on both left and right ends
*/
String.prototype.trim=function()
{
return this.replace(/(^/s*)|(/s*$)/g, “);
}
/**
* Delete the space on the left
*/
String.prototype.ltrim=function()
{
return this.replace(/(^/s*)/g,”);
}
/**
* Delete the space on the right
*/
String.prototype.rtrim=function()
{
return this.replace(/(/s*$)/g,”);
}
</script>
Examples of use are as follows:
The code copy is 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>
Plan 2:
Called in tool form, that is, trim(obj), this method can be used for special processing needs, and the definition is as follows:
The code copy is as follows:
<script type="text/javascript">
/**
* Delete spaces on both left and right ends
*/
function trim(str)
{
return str.replace(/(^/s*)|(/s*$)/g, “);
}
/**
* Delete the space on the left
*/
function ltrim(str)
{
return str.replace(/(^/s*)/g,”);
}
/**
* Delete the space on the right
*/
function rtrim(str)
{
return str.replace(/(/s*$)/g,”);
}
</script>
Examples of use are as follows:
The code copy is 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>