The JavaScript has substring()
method returns the part of the string
between the start and end indexes, or to the end of the string. But slice()
also another way to get substring from string. There are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.
Table of Contents
Extract last ‘n’ character
syntax:
1. substring(str.length - n)
2. slice(-n)
Let suppose we want to extract last 4 character of string then we can do like below
// Displays 'illa' the last 4 characters let str= 'Mozilla' let str1 = str.substring(str.length - 4) console.log(str1) let str2= str.slice(-4) console.log(str2)
Get last character of string.
// Displays 'a' the last 1 characters let str= 'Mozilla' let str1 = str.substring(str.length - 1) console.log(str1) let str2= str.slice(-1) console.log(str2)
substring vs slice
Substring | Slice |
---|---|
The substring() method swaps its two arguments if indexStart is greater than indexEnd See Example 1 | The slice() method returns an empty string if this is the case.See Example 1 |
If either or both of the arguments are negative or NaN , the substring() method treats them as if they were 0 .See Example 2 and 3 | slice() also treats NaN arguments as 0 , but when it is given negative values it counts backwards from the end of the string to find the indexes.See Example 2 and 3 |
Syntax:substring(indexStart) substring(indexStart, indexEnd) | Syntax:slice(beginIndex) slice(beginIndex, endIndex) |
Example of slice and substring
example: 1
let text = 'Mozilla' console.log(text.substring(5, 2)) // => "zil" console.log(text.slice(5, 2)) // => ""
example: 2
let text = 'Mozilla' console.log(text.substring(-5, 2)) // => "Mo" console.log(text.substring(-5, -2)) // => ""
example: 3
let text = 'Mozilla' console.log(text.slice(-5, 2)) // => "" console.log(text.slice(-5, -2)) // => "zil"