How to Get Last 2 Characters of String in Javascript?

10-Apr-2023

.

Admin

How to Get Last 2 Characters of String in Javascript?

In this quick example, let's see How to select last two characters of a string. if you have question about How to Get the Last Two Characters of a String in JavaScript then I will give simple example with solution. This article goes in detailed on JavaScript - get last 2 characters of string. I’m going to show you about how to extract the last two characters of a string? (JavaScript). You just need to some step to done get last 2 characters of string in javascript.

There are multiple ways to get the last 2 characters of a string in JavaScript. Here are some examples:

Example 1: Using substring() method


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Get Last 2 Characters of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "Hello World";

let lastTwoChars = str.substring(str.length - 2);

console.log(lastTwoChars); // Output: ld

</script>

</html>

Example 2: Using slice() method

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Get Last 2 Characters of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "Hello World";

let lastTwoChars = str.slice(-2);

console.log(lastTwoChars); // Output: ld

</script>

</html>

Example 3: Using substr() method

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Get Last 2 Characters of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "Hello World";

let lastTwoChars = str.substr(-2);

console.log(lastTwoChars); // Output: ld

</script>

</html>

Example 4: Using charAt() method

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Get Last 2 Characters of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "Hello World";

let secondLastChar = str.charAt(str.length - 2);

let lastChar = str.charAt(str.length - 1);

console.log(secondLastChar + lastChar); // Output: ld

</script>

</html>

#JavaScript