JavaScript: String.prototype.slice
str.slice(start)
- Return a substring from index start to end.
str.slice(start, end)
- Return a substring from index start to end.
(think of index as between the chars. Index 0 is before first character. Index 1 is after first character.)
const ss = "abcd"; console.log( ss.slice(1,3) ); // bc // think of index as between characters // index before first char is 0 // index after last char is length // negative index counts from the end, right to left console.log( ss.slice(0, ss.length) ); // abcd console.log( ss.slice() ); // abcd console.log( ss.slice(1) ); // bcd console.log( ss.slice(-1) ); // d console.log( ss.slice(-2) ); // cd // same index, empty string console.log( ss.slice(2, 2) === "" ); // true // when start index is greater than end index, result is empty string console.log( ss.slice(3, 2) === "" ); // true console.log( ss.slice(-2, -3) === "" ); // true
Note: "ð".length === 2
[see JavaScript: String Code Unit]