How to get the last character of a string?

Viewed 733417

How to get the last character of the string:

"linto.yahoo.com."

The last character of this string is "."

How can I find this?

15 Answers

An easy way of doing it is using this :)

var word = "waffle"
word.endsWith("e")

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

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

console.log(last);

Read more about at here

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 throws 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);

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");

var string = "Hello";
var fg = string.length;
fg = fg - 1;
alert(string[fg]);

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.

Related