JavaScript slice() String | Extract Substring from String

JavaScript slice() String | Extract Substring from String

In this tutorial, you will learn all about JavaScript String slice() method and how to use it.

Sometimes, when you work with javascript strings and you want to extract a substring or part of the string from a given string using the js built-in string method. Hence, this tutorial is very helpful for you.

JavaScript String slice() method

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

The syntax of slice() method is the following:

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

Here,

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

Note that, some important thing about the js string slice()  method parameters,

  • If you ignore the end, the slice() extracts to the end of the string.
  • If the begin or end is negative, the slice() treats it as str.length + begin or str.length+ end.

Return a new string substring of given string included between the begin and end indexs.

Examples: JavaScript String slice() method

Let’s take look at examples of using the javascript string slice() method.

The following example shows uses of slice() 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

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

Next example shows how to extract part of a string from a given string using the javascript string slice() and indexOf() method, see the following:

let email = '[email protected]'
let newStr = email.slice(0,email.indexOf('@'));

console.log(newStr); // mygmail

The following example shows, how to extract only the last character from a given string, see the following:

var str = "Hello world!";
var res = str.slice(-1);

console.log(res); // !

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.

Leave a Reply

Your email address will not be published. Required fields are marked *