Home  >  Article  >  Web Front-end  >  Solution to the problem that the javascript trim function cannot be used in IE_jquery

Solution to the problem that the javascript trim function cannot be used in IE_jquery

WBOY
WBOYOriginal
2016-05-16 16:36:31887browse

The trim function of JavaScript can be used under Firefox without any problem

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

There is no problem when using this method under Firefox, but an error occurs under IE
Then we can modify it

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

Add this sentence to the header, and the above can be run under both IE and FF

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>
Statement:
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