Removes spaces between the left and right sides of a string. In most programming languages, such as PHP and vbscript, trim, ltrim, or rtrim can be easily implemented. However, these three built-in methods are not available in js and need to be compiled manually. The following implementation method uses a regular expression, which is efficient and adds the three methods to the built-in methods of the String object.
The method format for writing a class is as follows: (str. trim ();)
<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>
You can write a function as follows: (trim (str ))
<Script type = "text/javascript"> function trim (str) {// Delete the leading and trailing spaces return str. replace (/(^ s *) | (s * $)/g, "");} function ltrim (str) {// Delete the left space return str. replace (/(^ s *)/g, "");} function rtrim (str) {// Delete the right space return str. replace (/(s * $)/g, "") ;}</script>
This is a face-to-face question from lgzx. It is required to add a method to the String of js to remove blank characters (including spaces, tabs, and page breaks) on both sides of the String ).
String. prototype. trim = function () {// return this. replace (/[(^ s +) (s + $)]/g, ""); // removes the blank characters in the string. // return this. replace (/^ s + | s + $/g, ""); // return this. replace (/^ s +/g ,""). replace (/s + $/g ,"");}
JQuery1.4.2, used by Mootools
function trim1(str){return str.replace(/^(s|xA0)+|(s|xA0)+$/g, '');}
JQuery1.4.3 and Prototype are used. This method removes g to slightly improve the performance when processing strings on a small scale.
function trim2(str){return str.replace(/^(s|u00A0)+/,'').replace(/(s|u00A0)+$/,'');}
Steven Levithan proposed the fastest way to crop strings in Javascript after performing performance tests. This provides better performance when processing long strings.
function trim3(str){str = str.replace(/^(s|u00A0)+/,'');for(var i=str.length-1; i>=0; i--){if(/S/.test(str.charAt(i))){str = str.substring(0, i+1);break;}}return str;}
Finally, we need to mention that the native trim method (15.5.4.20) is added to the String in the ECMA-262 (V5 ). In addition, the trimLeft and trimRight methods are added to the String in the engine Molliza Gecko 1.9.1.