Difference between SubStr() and SubString()
SubString():
The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1,4) == str.substring(4,1).
If either "start" or "stop" is less than 0, it is treated as if it were 0.
Syntax: string.substring(start,end)
Eg:
var str = ”Differences”;
alert(str.substring(0, 4)); // would print "Diff"
SubStr():
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
Syntax: string.substr(start,length)
Eg: var str = "Differences"
alert(str.substr(0, 4)); // this will also return "Diff"
We have seen how both functions work but if u have identified there is a difference how both functions work.
Both functions used to extract string
Both functions have 2 parameters
Both functions have initial parameter as starting position
But both functions dosen’t have same second parameter
SubStr() has end position as second parameter
SubString() has length as second parameter
Though above example returns same result, but here logic is different, as here starting index is zero and length of substring is 4, which means four characters long string, which starts from first character, that's why "Diff". If we apply different argument we will get different result.So the result of both functions return different which can be seen in below example
var str = "JavaScript"
alert(str.substr(4, 6)); // this will return Script
alert(str.substring(4, 6)); // this will return "Sc"
Here, you can clearly see that both substr and substring are returning different result, because starting index is not zero. Because of this many web developer often confuse and they think that substr and substring behave identically, which is not true. You should be very careful, while using substr() and substring(), otherwise it will create hard to find subtle bugs. There is another method called slice() which can also be used for creating smaller substring from String in JavaScript, and you can think of it to avoid any confusion between substring and substr in JavaScript.
No comments:
Post a Comment