JavaScript substr and substring: Difference between string functions

JavaScript string functions substring and substr has differences to their first and second arguments:

Syntax

Syntax of substr and substring is different but the result the effect of second argument is different

substr syntax

substr (from, length)

sysbtring syntax

substring (from, to)


First argument:

In substr, 1st argument accept negative (-ve) index to start counting from end (i.e. reverse start).

In substring, 1st argument's negative value treated as zero (0).

Examples:

"abcdefg".substr(-3,2);//"ef"
"abcdefg".substring(-3,2);//"ab"

Second argument of substr and substring difference:

In substr, the 2nd argument is the maximum length to return.

In substring, the 2nd argument is the index to before that to return (i.e. before the character of 2nd index is excluded).


Examples:

"abcdefg".substr(2,4); //returns "cdef"
"abcdefg".substring(2,4); //returns "cd"
Posted Status in Programming
Login InOR Register