Javascript Flashcards
How to remove the last character from a string in JavaScript?
myString.slice(0, -1)
The -1 in the second argument position may be confusing. This is because slice supports negative indexing. So -1 specifies 1 character from the end, -2 two characters from the end, etc.
const myString = “Learning JavaScript, one method at a time!”
const myStringSliced= myString.slice(0, -1);
console.log(myStringSliced); // “Learning JavaScript, one method at a time”
How to Find the First and Last Character of a String in JavaScript ?
(Using charAt() Method)
character = str.charAt(index)
In this approach, we are using the charAt() method, to access the first and last characters of a string by specifying indices 0 and length – 1, respectively.
How to Find the First and Last Character of a String in JavaScript ?
(Using Bracket Notion)
In this approach we are using bracket notation like str[0] accesses the first character and str[str.length – 1] accesses the last character of a string.
let str = “JavaScript”;
let firstChar = str[0];
let lastChar = str[str.length - 1];
console.log(“First character:”, firstChar);
console.log(“Last character:”, lastChar);
Note: this one runs faster
How to Find the First and Last Character of a String in JavaScript ?
(Using String.slice() Method)
Syntax
string.slice(startingIndex, endingIndex)
In this approach we are using slice() method on a string extracts characters. For first character, use str.slice(0, 1), for last character, use str.slice(-1).