804

How to get the last character of the string:

"linto.yahoo.com." 

The last character of this string is "."

How can I find this?

1
  • function getLastCharacter(name) { return name.substr(-1) } console.log(getLastCharacter("Sam")); // "m" Commented Mar 6, 2022 at 17:03

15 Answers 15

1449

An elegant and short alternative, is the String.prototype.slice method.

Just by:

str.slice(-1); 

A negative start index slices the string from length+index, to length, being index -1, the last character is extracted:

"abc".slice(-1); // "c"; 
Sign up to request clarification or add additional context in comments.

8 Comments

Side note: arrays also have a slice() method. - Their functionality is conceptually similar (partial copies) -------- (Just in case you're reading code and see .slice())
What do you mean by a "UTF-8 string"? The phrase makes no sense. FWIW though, JavaScript strings are funny beasts themselves: they are sequences of unsigned 16-bit integer values. If the intent of your string is to store characters, then the code above returns the last 16-bit value, which would not be pretty if it was the second part of a surrogate pair. But again, what exactly do you mean by "UTF-8 string"? UTF-8 is an encoding scheme that might make sense if you had a byte array, but means nothing at all when it comes to strings. Just curious.
@Egg, seems that you didn't try my example, str.slice(-1) does indeed get the last character of the string (as the OP required), just as if you used str.charAt(str.length - 1), try: "abc".slice(-1). I was showing here a usage of String.prototype.slice with a negative index. str.slice(-n) will get the last n characters of the original string as a new string value. More info: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@CMS You are right, your method does actually grab the last char of the string without trimming it. Nice elegant method too. For some reason I was thinking it was going to trim those chars and return a trimmed string. Sorry about that, I feel like an idiot for not trying it first.
This code may be short and "sexy" but I won't use it. The code is not self explanatory and not clear. Use charAt instead.
|
136

Use charAt:

The charAt() method returns the character at the specified index in a string.

You can use this method in conjunction with the length property of a string to get the last character in that string.
For example:

const myString = "linto.yahoo.com."; const stringLength = myString.length; // this will be 16 console.log('lastChar: ', myString.charAt(stringLength - 1)); // this will be the string

Comments

105

You can achieve this using different ways but with different performance,

1. Using bracket notation:

var str = "Test"; var lastLetter = str[str.length - 1];

But it's not recommended to use brackets. Check the reasons here

2. charAt[index]:

var lastLetter = str.charAt(str.length - 1)

This is readable and fastest among others. It is most recommended way.

3. substring:

str.substring(str.length - 1);

4. slice:

str.slice(-1);

It's slightly faster than substring.

You can check the performance here

With ES6:

You can use str.endsWith("t");

But it is not supported in IE. Check more details about endsWith here

3 Comments

No need to do performance squeezing on current machines. Use the most concise solution. My vote is on str.slice(-1);
I'm not sure how endsWith fits here, that does something completely different.
Re: bracket notation(BN) 1/ This is 2022, screw IE7. 2/ Coders trying to put chars with BN shouldn't be coding.
81
str.charAt(str.length - 1) 

Some browsers allow (as a non-standard extension) you to shorten this to:

str[str.length - 1]; 

1 Comment

Outdated answer. Using bracket notation is not a non-standard extension.
41

Use substr with parameter -1:

"linto.yahoo.com.".substr(-1);

equals "."

Note:

To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).

2 Comments

Seems like this one is as shorter as slice(), I wonder wich one is better and faster.
substr is a legacy feature and is optional outside of web browsers. slice is better.
35

Using the String.prototype.at() method is a new way to achieve this

const s = "linto.yahoo.com."; const last = s.at(-1); console.log(last);

Read more about at

1 Comment

exactly what I wanted to see. Slice works, but if you read slice() vs at(); What's more readable: "string".at(pos) vs "string".slice(pos) There's also "string".charAt() and I would say that is better than slice() but less desirable than at()
12

Try this...

const str = "linto.yahoo.com." console.log(str.charAt(str.length-1)); 

Comments

10

You can get the last char like this :

var lastChar=yourString.charAt(yourString.length-1); 

Comments

7
var firstName = "Ada"; var lastLetterOfFirstName = firstName[firstName.length - 1]; 

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!
5

Use the JavaScript charAt function to get a character at a given 0-indexed position. Use length to find out how long the String is. You want the last character so that's length - 1. Example:

var word = "linto.yahoo.com."; var last = word.charAt(word.length - 1); alert('The last character is:' + last); 

Comments

5

If you have or are already using lodash, use last instead:

_.last(str); 

Not only is it more concise and obvious than the vanilla JS, it also safer since it avoids Uncaught TypeError: Cannot read property X of undefined when the input is null or undefined so you don't need to check this beforehand:

// Will throw Uncaught TypeError if str is null or undefined str.slice(-1); str.charAt(str.length -1); // Returns undefined when str is null or undefined _.last(str); 

1 Comment

It's important to note that this could cause you to run into other issues, such as expecting it to return a string when it really returns undefined. This could be useful in some cases but in general it's probably better to just use try...catch
2

You can use the following. In this case of last character it's an overkill but for a substring, its useful:

var word = "linto.yahoo.com."; var last = ".com."; if (word.substr(-(last.length)) == last) alert("its a match"); 

Comments

1

You can simplify using .at(-1)

let string = "linto.yahoo.com." console.log(string.at(-1) 

Comments

0

You can use substring() method :

let string = "linto.yahoo.com."

console.log(string.substring(string.length-1))

1 Comment

This answer appears to be a duplicate from the one provided by Vikas.
-3

You can use this simple ES6 method

const lastChar = (str) => str.split('').reverse().join(',').replace(',', '')[str.length === str.length + 1 ? 1 : 0]; // example console.log(lastChar("linto.yahoo.com."));

This will work in every browsers.

4 Comments

it won't work if the original string had commas in it -1
It's sooo complicated. If you want to convert it to an array and reverse it, why not just (str) => str.split('').reverse()[0]? :)
Some people do not understand second degree
This is hilarious, thanks vdegenne! Obviously the slice(-1) answer with all the upvotes is the best one, but this one does put me in mind of a relatively terse alternative that nobody else seems to have suggested: const lastChar=str.split('').pop()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.