Home

Substring vs. slice in JavaScript

Substring

The syntax of substring is:

str.substring(indexStart[, indexEnd])

Output will be of type string. While using substring you need to know the indexes both the start and end, so it'll work nice with hard coded strings or any fixed type of strings.

Examples

const message = 'My phone no. is 123456789'

console.log(message.substring(16))
// Output → '123456789'

console.log(message.substring(3,8))
// Output → 'phone'

// If indexStart is greater than indexEnd, javascript substring swaps it for you.
console.log(message.substring(8,3))
// Output → 'phone'

console.log(message.substring(3,3))
// Output → ''

console.log(message.substring(message.length-9))
// Output → '123456789'

// NaN is considered as 0
console.log(message.substring('asd',4))
console.log(message.substring(4,'asd'))
// Output → 'My p'

// Negative number is considered as 0
console.log(message.substring(4,-4))
console.log(message.substring(-4,4))
// Output → 'My p'

String.prototype.substr(…) is not strictly deprecated but considered a legacy function and should be avoided whenever possible.
Use substring() instead of substr().

Slice

The syntax of slice is:

str.slice(beginIndex[, endIndex])

Output will be of type string. In Most of the cases slice is similar to substring except for negative numbers and cases where beginIndex is greater than endIndex.

console.log(message.slice(16))
// Output → '123456789'

console.log(message.slice(3,8))
// Output → 'phone'

console.log(message.slice(3,3))
// Output → ''

console.log(message.slice(message.length-9))
// Output → '123456789'

// NaN is considered as 0
console.log(message.slice('asd',4))
// Output → 'My p'

// If a negative number is given slice() counts backwards from the end of the string to find the indexes
console.log(message.slice(4,-4))
// Output → 'hone no.: is 12345'

console.log(message.slice(-9))
// Output → '123456789'

console.log(message.slice(-9,24)) // here -9 means message.length-9 which is 16
// Output → '12345678'

// If beginIndex is greater than endIndex, javascript slice returns empty string.
console.log(message.slice(-4,4)) // here -4 means message.length-4 which is 21
console.log(message.slice(8,3))
console.log(message.slice(4,'asd')) // NaN is considered as 0
// Output → ''

Comparison of substring() and slice()

If indexStart is greater than indexEnd:

For NaN:

For Negative numbers:



Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments