String Slicing in JavaScript and Python
I am posting this so that you don’t scratch your head with string slicing in JavaScript like me if you are coming from a Python background.
I spent some gray cells today while working on a capitalize function in JavaScript. The function simply takes a word as an input and capitalizes it.
I thought that since a string is an iterable, I could slice it with the indexes. So, I can get index 0, convert it to upper case, and then add [1:] as the remainder of the word.
Unfortunately that trick from Python did not work in JavaScript; Python’s [start_index:end_index] does not work. JavaScript only allows to access one index, not a range.
Therefore, the JavaScript method that we need to use is the slice(start_index, end_index). But since JavaScript does not figure out the end_index automatically, we need to get it by the string.length method.
function capitalize(word){
return word[0].toUpperCase() + word.slice(1, word.length);
}