1

I am coming from a python background and do not understand this, is there a way in javascript to get the last 2nd element of a string?

eg const name = "John"

the closest i could find is name.slice(-2) but it return two characters, in other words, including the last character as well, which is not want i want.

3
  • name.charAt(name.length-2)? Commented Apr 27, 2021 at 22:18
  • sadly, javascript doesn't support negative indexing like python. Commented Apr 27, 2021 at 22:31
  • @georg thats my point. thanks Commented Apr 27, 2021 at 22:33

3 Answers 3

2

JS's slice isn't that similar to Python's slice syntax in spite of the name similarity. JS's slice with a single argument always goes from the provided number to the end of the string or array unless you specify a stop index as well (inclusive, exclusive):

const name = "John";

console.log(name.slice(-2, -1));
console.log(name[name.length-2]); // or use a normal index since you want 1 char

Sign up to request clarification or add additional context in comments.

Comments

1

Strings in JavaScript are arrays. For example, you can get the letter "h" in the word "John" by doing name[2].

In this case, we can use the .length property of an array to get the amount of elements in that array, and then subtract 2 to get the second last element in it. Like so:

let name = "John"
let secondLast = name[name.length - 2]

console.log(secondLast)

Subtracting 2, because the length of an array is a count, starts from 1, but array indexes are starting from 0. And we need the second last letter, not the last one.

Comments

0

The slice() function takes two arguments, start and end. You can also index it like an array.

So you could write:

const name = "John"
console.log(name.slice(-2,-1))

console.log(name[name.length-2])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.