In javascript, if you want to remove spaces between the left and right sides of the string, you can use the trim, ltrim, or rtrim function in vbs, and you will find an error, if you do not have these three functions in js, You need to customize them. Next I will introduce you to the trim, ltrim, or rtrim methods in js. For details, refer.
The method format for writing classes is as follows: (str. trim ();) We use regular expressions to operate
The Code is as follows: |
Copy code |
<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> |
Or write it like this.
The Code is as follows: |
Copy code |
Function trim (str ){ For (var I = 0; I <str. length & str. charAt (I) = ""; I ++ ); For (var j = str. length; j> 0 & str. charAt (J-1) = ""; j --); If (I> j) return ""; Return str. substring (I, j ); } |
You can write a function as follows: (trim (str ))
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Function trim (str) {// Delete spaces between the left and right sides 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> |
S. replace (/(^ s *) | (s * $)/g, ""); (^ s *) | (s * $)
First, replace/(^ s *) | (s * $)/g ""
Then ,/... /g indicates the place where the wildcard is placed. g indicates the global parameter. (^ s *) or (s * $) will be replaced ""
Regular Expression that matches the first and last blank characters: ^ s * | s * $ can be used to delete the white space characters (including spaces, tabs, break characters, and so on) at the end of the first line of a line. It is a very useful expression.