There are many places where we need to use trim in JavaScript, but JavaScript does not have an independent trim function or method to use, so we need to write a trim function ourselves to achieve our purpose.
Option one:
Called in prototype mode, that is, in the form of obj.trim(), this method is simple and widely used. It is defined as follows:
<script language="javascript">
/**
* Delete spaces at both 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>
Usage examples are 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>
Option two:
Called in tool mode, that is, in the form of trim(obj), this method can be used for special processing needs, and is defined as follows:
<script type="text/javascript">
/**
* Delete spaces at both ends
*/
function trim(str)
{
return str.replace(/(^s*)|(s*$)/g, ”);
}
/**
* Delete the space on the left
*/
functionltrim(str)
{
return str.replace(/(^s*)/g,”);
}
/**
* Delete the space on the right
*/
functionrtrim(str)
{
return str.replace(/(s*$)/g,”);
}
</script>
Usage examples are 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>