Javascript - Extracting String Parts

Introduction

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

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

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 starting index (position), and the ending index (position).

This example slices out a portion of a string from position 7 to position 13:

Demo

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var res = str.slice(7,13);
console.log(res);

Result

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:

Demo

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var res = str.slice(-12,-6);
console.log(res);

Result

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

Demo

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var res = str.slice(7);
console.log(res);

Result

or, counting from the end:

Demo

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var res = str.slice(-12)
console.log(res);

Result

The substring() Method

substring() is similar to slice().

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

Demo

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var res = str.substring(7,13);
console.log(res);

Result

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

The substr() Method

In the substr() method the second parameter specifies the length of the extracted part.

Demo

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var res = str.substr(7,6);
console.log(res);

Result

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

The second parameter can not be negative, since it defines the length.

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

Related Topic