Powered by Blogger.

JavaScript–substring, substr and slice


JavaScript contains 3 functions for manipulating strings namely substring, substrate, and slice. It's very important to know the difference between these three.

Firstly, let's look at “substring”, it accepts 2 parameters (as a matter of fact all 3 accept 2 parameters ), both numbers, first one is the start character position and second is an end character position.  Let's look at 3 examples below


In the first example, we see that for the substring(6,13), it returns a string from position 6 to 13, things become interesting in the second and third examples. If we have start and end as the same position, substring returns an empty string, and if in case the end position is smaller than the start position then substring swaps the values, in the above example substring take to start as 3 and end as 6 positions.

Next Up, substr, here the first parameter is started character position and the second parameter is the number of characters to be extracted. Let's look at same 3 examples as above but using substr


Here we see that first and fourth example returning the same value that’s because JavaScript does not throw an error if the second parameter is more than the number of characters in a string, it just returns the remaining string from the specified starting point.

Lastly, its slice, Slice is similar to Array slice function in JavaScript. The behavior of slice is almost similar to substring except for one difference if the end value is less than start value slice will not swap the values but instead return an empty string


It's very easy to confuse substring with substr because their name is quite similar, but it's very important to remember that in substring end parameter tells us the character position and in substrate end, parameter tells us about the number of characters from the start position. We should make sure we use the consistent mechanism in our applications.

No comments