How to Get Last Character of String in Javascript?

05-Apr-2023

.

Admin

How to Get Last Character of String in Javascript?

Today, How to get the last character of a string is our main topic. This article goes in detailed on javascript get last character of string. you will learn get last character of string javascript. we will help you to give example of find last character of string javascript. follow bellow step for select last character of string javascript.

To get the last character of a string in JavaScript, you can use the charAt() method with the length of the string minus one as its argument. Here's an example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get Last Character of String in Javascript?</title>

</head>

<body>

</body>

<script type="text/javascript">

const myString = "Hello World";

const lastChar = myString.charAt(myString.length - 1);

console.log(lastChar); // Output: d

</script>

</html>

Alternatively, you can also use square brackets and the index of the last character to get it directly:

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get Last Character of String in Javascript?</title>

</head>

<body>

</body>

<script type="text/javascript">

const myString = "Hello World";

const lastChar = myString[myString.length - 1];

console.log(lastChar); // Output: d

</script>

</html>

Both methods will give you the same result.

#JavaScript