JavaScript slice() String: Extract Substring from String

Extract substring from string in JavaScript; Through this tutorial, i am going to show how to extract substring from string in javascript using slice() method and without regex.

JavaScript slice() String: Extract Substring from String

The js stringslice() method extracts a part of a string (substring) and returns a new string.

Syntax of JavaScript slice method

See the following syntax of javaScript slice() method; as shown below:

let substr = str.slice(begin [, end ]);

Explanation of above given slice method syntax; as follow:

  • The begin is a position where to start the extraction.
  • The end  is a position where to end the extraction.

Example 1 -javascript extract substring from string with start index

Take an example using javaScriptslice() method to extract part of string from a given string with beingIndex:

let str = 'Hello JavaScript'
let newStr = str.slice(5);
console.log(newStr); // JavaScript

Example 2 -javascript extract substring from string with start index and end Index

The following example shows uses of slice() method, to extract part of string from a given string with beingIndex and endIndex:

let str = 'Hello JavaScript'
let newStr = str.slice(0, 5);
console.log(newStr); // Hello

Conclusion

In this tuorial, you have learned all about the JavaScript String slice() method and using this method extract a substring from a given string.

More JavaScript Tutorials

Leave a Comment