Home >Web Front-end >JS Tutorial >Javascript trim() function implementation
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 1:
Called in prototype mode, that is, obj.trim() form. This method is simple and widely used. It is defined as follows:
Usage examples are as follows:
alert(document.getElementById('abc').value.trim());
alert (document.getElementById('abc').value.ltrim());
alert(document.getElementById('abc').value.rtrim());
Option 2:
Called in tool mode, that is, in the form of trim(obj). This method can be used for special processing needs. The definition is as follows:
/ **
* Delete the spaces on the left and right sides
*/
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,”);
}
Usage examples are as follows:
alert(trim(document.getElementById('abc').value));
alert(ltrim(document.getElementById('abc').value));
alert(rtrim(document.getElementById('abc').value));
The above is an example of Javascript trim() function implementation. For more related content, please pay attention to the PHP Chinese website (www. php.cn) other articles.