String slice() method in JavaScript

You can use the slice in JavaScript for extracting some part of the string. slice method returns extracted string in a new string.

Syntax:

str.slice(startPosition, endPosition);

Explanation:

Apply slice method on str. You have to pass the following two arguments:
1) startPosition: index from which extracting is to be done.
2) endPosition: index to which end the extracting of string.
If this argument is not passed then the splice method extracts the rest of the string from startPosition.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>slice()</title>
  <script>
    var str = "HTML, CSS, JavaScript";
    var slicedString1 = str.slice(11, 21);
    document.write('slicedString is: ', slicedString1);
    document.write("<br />");
    var slicedString2 = str.slice(5);
    document.write('slicedString is: ', slicedString2);
  </script>
</head>
<body>
</body>
</html>

Output:

slicedString is: JavaScript
slicedString is: CSS, JavaScript

If negative parameters are passed then it starts counting from the end of the string. See the example below for negative parameters passed for a slice in JavaScript.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>slice()</title>
  <script>
    var str = "HTML, CSS, JavaScript";
    var slicedString = str.slice(-15, -12);
    document.write('slicedString is: ', slicedString);
  </script>
</head>
<body>
</body>
</html>

Output:

slicedString is: CSS

Additional Link:

String substring() method in JavaScript

2 Comments

Leave a Reply

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