Skip to content
the poor coder

javascript get last character in string

Poor Man
Published
Reading time
1 min read
On this page

How to Get the Last Character in a String Using JavaScript#

As a web developer, I often come across situations where I need to extract the last character from a string using JavaScript. Here are a few ways to accomplish that:

Method 1: Using the charAt() method#

The charAt() method is used to get the character at a specific index in a string. To get the last character, we need to subtract 1 from the length of the string and pass that value as an argument to the charAt() method.

Text

let str = "Hello World!";
let lastChar = str.charAt(str.length - 1);
console.log(lastChar); // Output: "!"

Method 2: Using the substr() method#

The substr() method is used to extract a substring from a string, based on the starting and ending indexes. To get the last character, we can pass the length of the string as the starting index and 1 as the second argument.

Text

let str = "Hello World!";
let lastChar = str.substr(str.length - 1, 1);
console.log(lastChar); // Output: "!"

Method 3: Using the slice() method#

The slice() method is also used to extract a substring from a string, based on the starting and ending indexes. To get the last character, we can pass -1 as the argument to the slice() method, which will start from the end of the string.

Text

let str = "Hello World!";
let lastChar = str.slice(-1);
console.log(lastChar); // Output: "!"

These are some of the ways to get the last character from a string in JavaScript. Depending on the situation, one method may be more appropriate than the others. It's important to understand the differences between them and choose the one that best fits your needs.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC