Javascript String slice()

Introduction

Javascript String slice() gets a sub string from a longer string.

The slice() method can accept one or two arguments.

str.slice(beginIndex[, endIndex])
  • beginIndex - the zero-based index to begin extraction.
  • endIndex - Optional, index to end extraction.

If beginIndex is negative, it is treated as str.length + beginIndex.

If beginIndex is greater than or equal to str.length, slice() returns an empty string.

The character at endIndex will not be included.

If endIndex is omitted, slice() extracts to the end of the string.

If endIndex is negative, it is treated as str.length + endIndex.

The slice() method does not alter the string itself.

It returns a string value as the result, leaving the original unchanged.

The following example uses slice() to create a new string.

let str1 = '12345678901234567890', 
    str2 = str1.slice(1, 8),//  ww  w  .  j a  va  2 s.co m
    str3 = str1.slice(4, -2),
    str4 = str1.slice(12),
    str5 = str1.slice(30);
console.log(str2)  
console.log(str3)  
console.log(str4)  
console.log(str5)  
let stringValue = "hello world"; 
console.log(stringValue.slice(3));        // "lo world" 
console.log(stringValue.slice(3, 7));     // "lo w" 

For the slice() method, a negative argument is treated as the length of the string plus the negative argument.

let stringValue = "hello world"; 
console.log(stringValue.slice(-3));         // "rld" 
console.log(stringValue.slice(3, -4));      // "lo w" 



PreviousNext

Related