Thursday, December 5, 2013

Javascript - String functions



String.substr() VS String.substring() String.substr(start,length) is different from String.substring(start,end).
The second parameter length in substr() specify the number of character to be extracted,
whereas the second parameter end in substring() specify the index of ending character in the string.
Do not mess these two up. And pay attendion to the effect of negative number as second parameter giving to these functions.



Further study please go to substr(), substring() and slice().
String.trim() is used to remove the trailing and leading space from a string variable.
However, this method is not add to Javascript standard until Version 1.8.
Therefore, IE 8 or belows have not implemented String.trim() method.

In order to add this method compatibility to the IE 8 or belows, we need to add the trim() method to the prototype of the String class.

Adding the followings to the script before any String.trim() is begin called:
if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}
Just like this article does, check out the source of this page.

No comments:

Post a Comment