whadiz.com: What is?
Advertisement
Search Articles:     Home | About | Tools | Contact Us
Games
Board Games
Online Games
Databases
Sql Server
Programming
Visual C# in ASP.Net
JavaScript
Humor
Satire
Web Design
Html

Clever Facts Section



What is JavaScript trim? | JavaScript trim | Trim using JavaScript | JavaScript trim remove spaces | Javascript Remove leading and trailing spaces | How To Eliminate Spaces

What is JavaScript trim?

Currently the JavaScript language does not have a JavaScript trim function for string variables. Programmatically the behaviour of JavaScript trim can be emulated by using regular expressions. Although some sort of loop can also be used, where leading and trailing spaces are removed from the string variable, the use of regular expressions to implement a JavaScript trim function is much more efficient. 

What is a general function for JavaScript trim?

<script language="JavaScript" type="text/javascript">
    function trim(str) {
        return str.replace(/^\s+|\s+$/g,"");
    }
</script>

This function is simply called as follows:

var mystr;
mystr = trim(" hello ");

The regular expression replaces any spaces at the beginning of the string parameter, as well as any spaces at the end of the string parameter.

How to implement JavaScript trim by extending the String prototype?

JavaScript trim can be implemented by extending the String prototype as follow:

<script language="JavaScript" type="text/javascript">
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g,"");
    }
</script>

This JavaScript trim function can then be called as a method of any String type:

var mystr = new String(" ABC ");
mystr=mystr.trim();

How can the JavaScript trim function be modified if efficiency is an issue?

Simply use the following line to implement JavaScript trim:

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

In essence, instead of performing the JavaScript trim in one go, a right trim and a left trim is performed seperately.

The speed increase is seen when this JavaScript Trim function is applied to longer strings. The speed increase is largely due to optimizations internally to how regular expressions are handled by JavaScript.

What browser compatibility issues exist with the above JavaScript trim function?

Regular expressions can be used with JavaScript version 1.2 and above. Microsoft Internet Explorer 4 and above, Netscape 4 and above, all versions of Firefox, and most other modern web browsers support JavaScript 1.2.

Link to this article:

Browse some more: Next Article | Next Fact | More JavaScript Articles | More Clever Facts


Copyright © 2014 whadiz.com. All rights reserved.
whadiz.com: What is JavaScript trim? | JavaScript trim | Trim using JavaScript | JavaScript trim remove spaces | Javascript remove leading and trailing spaces | How To Eliminate Spaces
Home of the answer "what is"
Website designed by IT Trader & hosted by CMWeb