Home > Article > Web Front-end > How to remove spaces from the beginning and end of a string in javascript
Method: 1. Use the "substring(Math.max(this.search(/\S/),0),this.search(/\S\s*$/) 1)" statement; 2 , use the "replace(/^\s /,'').replace(/\s $/,'')" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer
##javascript Remove spaces from the beginning and end of the string
1. substring() intercepts all characters from the index of the first non-space character to the index of the last non-space character, and returns the intercepted characters StringString.prototype.trimOne = function () { return this.substring(Math.max(this.search(/\S/), 0), this.search(/\S\s*$/)+1) };2. The replace() method replaces all the spaces at the beginning of the string with an empty string, and then replaces all the spaces at the end of the character bed with an empty string
String.prototype.trimTwo = function () { return this.replace(/^\s+/, '').replace(/\s+$/, ''); };Improve and simplify it, and it looks more elegant.
String.prototype.trimThree = function () { return this.replace(/^\s+|\s+$/g, '') };[Related recommendations:
The above is the detailed content of How to remove spaces from the beginning and end of a string in javascript. For more information, please follow other related articles on the PHP Chinese website!