How to Extract a Substring in Javascript?

Contents

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( )

str.substring(indexStart[, indexEnd])
  • 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 :

<script>
  function strFunction() {
    var str = "REVISIT CLASS";
    var res = str.substring(1, 4);
    document.write(res + "<br>"); 
}
</script>

Output

EVI

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()

str.substr(start[, length])
  • start – Starting index of the string
  • length = number of characters to return.
<script>
   function myFunction() {
	var str = "REVISIT CLASS";
	var res = str.substr(1,4);
	document.write(res + "<br>"); 
  }
</script>

Output

EVIS

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()

str.slice(beginIndex[, endIndex])
  • beginIndex – starting position of the string to begin extraction.
  • endIndex – ending position of the string to end extraction.

Example

<script>
function myFunction() {
	var str = "REVISIT CLASS";
	var res = str.slice(1,4);
	document.write(res + "<br>"); 
}
</script>

Output

EVI

Recommended Articles