Workaround:
Method 1:
Use the global function in jquery $.trim () instead of the native JS method Trim (): $.trim ($ ("input[type= ' text ']:eq (0)"). Val (). Trim ());
Method 2:
To extend the string method using native JS
1. Methods written as class: [Calling Format: Str.trim (); ]
The code is as follows |
Copy Code |
<script type= "Text/javascript" > Function.prototype.method = function (name, func) { This.prototype[name] = func; return this; }; if (String.prototype.trim) {//whether the browser has its own trim () method String.method (' Trim ', function () { Return This.replace (/^s+|s+$/g, ""); }); String.method (' LTrim ', function () { Return This.replace (/^s+/g, ""); }); String.method (' RTrim ', function () { Return This.replace (/s+$/g, ""); }); } </script> |
Example
The code is as follows |
Copy Code |
<input id= "Demo" type= "value=" has space "/> <a href=" javascript:; "onclick=" Test (); " > Click to remove Space </a> <script type= "Text/javascript" > Function.prototype.method = function (name, func) { This.prototype[name] = func; return this; }; if (! String.prototype.trim) {//Determine if the browser has its own trim () method String.method (' Trim ', function () { Return This.replace (/^s+|s+$/g, ""); }); String.method (' LTrim ', function () { Return This.replace (/^s+/g, ""); }); String.method (' RTrim ', function () { Return This.replace (/s+$/g, ""); }); } Test Call Method: Trim () document.getElementById ("Demo"). Select (); var Str=document.getelementbyid ("Demo"). Value; function Test () { document.getElementById ("Demo"). Value=str.trim (); Can be replaced with Str.ltrim () or Str.rtrim () document.getElementById ("Demo"). Select (); } </script> |
Workaround Two
Write function: [Call Format: Trim (str)]
The code is as follows |
Copy Code |
<script type= "Text/javascript" > function Trim (str) {//Remove spaces at left and right ends Return Str.replace (/(^s*) | ( s*$)/g, ""); } function LTrim (str) {//delete left space Return Str.replace (/(^s*)/g, ""); } function RTrim (str) {//Remove the right space Return Str.replace (/(s*$)/g, ""); } </script> |
Instance
The code is as follows |
Copy Code |
<input id= "demo" type= "value=" have space "/> <a href=" javascript:; "onclick=" Test (); " > Click to remove Space </a> <script type= "text/javascript" function trim (str) {//remove spaces on both sides return Str.replace (/(^s*) | ( s*$)/g, ""); } Function LTrim (str) {//delete left space return str.replace (/(^s*)/g, ""); function RTrim (str) {//delete the right space return str.replace (/(s*$)/g, ""); //Test Invocation method: Trim () document.getelementbyid ("Demo"). Select (); var str= document.getElementById ("Demo"). Value; function Test () { document.getelementbyid ("Demo"). Value=trim (str);//Can be replaced by Str.ltrim () or Str.rtrim ( document.getelementbyid ("Demo"). Select (); } </script> |