Considering I work with PHP day in and day out, it is no wonder that I completely forgot that JavaScript also comes up with its super handy substring function, for when you need to grab only a specific part of a string (much like PHP’s substr function).

string.substring(from, to)

The JavaScript substring() method extracts the characters from a string, between two specified indices, and returns the new sub string. In extracts the characters in a string between “from” and “to”, not including “to” itself.

Two parameters, the first required, the second optional. In our example above, from indicates the index where to start the extraction – remember, the first character is at index 0. The second, optional parameter is to, which if specified indicates the index where to stop the extraction. If omitted, substring extracts the rest of the string.

In action:

var str="Hello world!";
document.write(str.substring(3)+"
"); document.write(str.substring(3,7));

The above will output:

lo world!
lo w

Useful.