I dont really understand how substring works


example i have a string of "hello world" and i want to get the string of 4th to 7th, because of the index start from 0, i assume that the formula should be like substring( from-1, until - 1 ) .

but to access that, why i need to write down like this substring( 3, 7 ) instead? is the format of substring substring( from-1, until+1 ) or ( from - 1, until - 1 )?


var text = "abcdefg"
Index:      0123456

If you were to select 0 to 4, for example, then here you would get "abcde" because they start at 0, and 4 is the 5th character. Do you get it?

3 to 7 would select the 4th,5th and 6th letters in your string, because index 3 is the 4th letter and it selects everything between that and index 7.


so it returns string element from until ( untilVariable - 1 ), isn't it?




@kevinmogi You're losing me a little with untilVariable - 1, but I think you understand it.

I'll show you a few examples just to make sure :wink:

» "Hello, World!".substring(0, 5);
← "Hello"
» "Codecademy".substring(0, 2);
← "Co"
» "0123".substring(0, 3);
← "012"

Put simply, when you call substring() on a string and specify a start and stop number and both of them (no negative integers, etc.. Nothing fancy or weird), then substring() starts at your start number (including it), then goes up to, but not including your end number.

Does this help you understand it?


this is what i mean with from until ( untilVariable - 1 ), but anyway thanks


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.