Javascript under IE trim function cannot use the solution
- 2020-03-30 03:55:18
- OfStack
In this paper, an example is given to analyze the solution that javascript trim function cannot be used under IE. Specific analysis is as follows:
First of all, javascript's trim function is fine with firefox:
<script language="javascript">
var test1 = " aa ";
test1 = test1.toString();
test1 = test1.trim();
</script>
This works fine in firefox, but it reports an error in IE!
To this, we can modify:
String.prototype.trim=function(){return this.replace(/(^s*)|(s*$)/g,"");}
Add this sentence to the top of the head, and the above one can run under both IE and FF:
<script language="javascript">
String.prototype.trim=function(){return this.replace(/(^s*)|(s*$)/g,"");}
var test1 = " aa ";
test1 = test1.toString();
test1 = test1.trim();
</script>
Methods provided by JQuery:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Show Trim Example</button>
<script>
$("button").click(function () {
var str = " lots of spaces before and after ";
alert("'" + str + "'");
str = jQuery.trim(str);
alert("'" + str + "' - no longer");
});
</script>
</body>
</html>
It is believed that this article has a good reference value to the compatibility design of WEB front-end browser using javascript.