How to Extract a Substring in Javascript?

Javascript is providing three different methods to extract the Substring from the given input string. The methods are listed below

  • string.Substring(index_start, index_end)
  • string.Substr(starting_index, length)
  • string.Slice(begin_index,end_index)

Substring() method

The substring method extract the part of the string from the starting index to ending index. The index of the first character is 0, the second character is 1 and so on. The end index is used to stop at (but not include in the output).

Syntax of Substring( )

  • IndexStart – The index of the first character to include in the returned substring.
  • IndexEnd – Optional. The index of the first character to exclude from the returned substring.

Example :

Output

Substr() method

The substr method extracting the part of the string, starting at the specified index and extending for a given number of characters afterward.

Syntax of substr()

  • start – Starting index of the string
  • length = number of characters to return.

Output

Slice() method

The slice method extracts the section of the string and returns as a new string. It is similar to substring() method.

Syntax of slice()

  • beginIndex – starting position of the string to begin extraction.
  • endIndex – ending position of the string to end extraction.

Example

Output

Recommended Articles