Javascript Flashcards

1
Q

How to remove the last character from a string in JavaScript?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to Find the First and Last Character of a String in JavaScript ?
(Using charAt() Method)

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to Find the First and Last Character of a String in JavaScript ?
(Using Bracket Notion)

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to Find the First and Last Character of a String in JavaScript ?
(Using String.slice() Method)

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly