Home > Web Front-end > JS Tutorial > Solution to the problem that javascript trim function cannot be used under IE_javascript tips

Solution to the problem that javascript trim function cannot be used under IE_javascript tips

WBOY
Release: 2016-05-16 16:36:17
Original
1346 people have browsed it

This article analyzes the solution to the problem that JavaScript trim function cannot be used under IE, which has certain reference value for web front-end design. The specific analysis is as follows:

First of all, there is no problem using JavaScript’s trim function under Firefox:

<script language="javascript"> 
 var test1 = "  aa  "; 
 test1 = test1.toString(); 
 test1 = test1.trim(); 
</script>

Copy after login

There is no problem when using this method under Firefox, but an error occurs under IE!

We can modify this:

String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g,"");} 

Copy after login

Add this sentence to the header, and the above can be 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> 
Copy after login

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>

Copy after login

I believe that what is described in this article has good reference value for everyone to use javascript to design the compatibility of WEB front-end browsers.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template