Remove the spaces on the left and right ends of the string. You can easily use trim, ltrim or rtrim in vbscript, but there are no these 3 built-in methods in js and need to be written manually. The following implementation method uses regular expressions, which are very efficient, and adds these three methods to the built-in methods of the String object.
The format of the method written into a class is as follows: (str.trim();)
The code copy is as follows:
<script language="javascript">
String.prototype.trim=function(){
return this.replace(/(^/s*)|(/s*$)/g, "");
}
String.prototype.ltrim=function(){
return this.replace(/(^/s*)/g,"");
}
String.prototype.rtrim=function(){
return this.replace(/(/s*$)/g,"");
}
</script>
Writing it as a function can be done like this: (trim(str))
The code copy is as follows:
<script type="text/javascript">
function trim(str){ //Delete spaces on both left and right ends
return str.replace(/(^/s*)|(/s*$)/g, "");
}
function ltrim(str){ //Delete the space on the left
return str.replace(/(^/s*)/g,"");
}
function rtrim(str){ //Delete the space on the right
return str.replace(/(/s*$)/g,"");
}
</script>
The above are two ways to remove spaces on both sides of strings by JavaScript. I hope you like it.