There are 3 methods for extracting a part of a string:

  • slice(startend)
  • substring(startend)
  • substr(startlength)

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the start position, and the end position (end not included).

This example slices out a portion of a string from position 7 to position 12 (13-1):

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);

The result of res will be:

Banana
 

Remember: JavaScript counts positions from zero. First position is 0.

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);

The result of res will be:

Banana

If you omit the second parameter, the method will slice out the rest of the string:

Example

var res = str.slice(7);

or, counting from the end:

Example

var res = str.slice(-12);
Negative positions do not work in Internet Explorer 8 and earlier.
 

The substring() Method

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);

The result of res will be:

Banana

If you omit the second parameter, substring() will slice out the rest of the string.
 

The substr() Method

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);

The result of res will be:

Banana

If you omit the second parameter, substr() will slice out the rest of the string.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7);

The result of res will be:

Banana, Kiwi
 

If the first parameter is negative, the position counts from the end of the string.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);

The result of res will be:

Kiwi



Practice Excercise Practice now