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) };
String.prototype.trimTwo = function () { return this.replace(/^\s+/, '').replace(/\s+$/, ''); };
String.prototype.trimThree = function () { return this.replace(/^\s+|\s+$/g, '') };
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!