How to Replace Last Character of String in Javascript?

06-Apr-2023

.

Admin

How to Replace Last Character of String in Javascript?

This post will give you example of how to replace last character of string in javascript. we will help you to give example of replace last character of string using javascript. you can understand a concept of javascript - replace last character in string. you'll learn replace the last character in a string in javascript. Alright, let’s dive into the steps.

There are multiple ways to replace the last character of a string in JavaScript. Here are some examples:

Example 1: Using substring and concatenation:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Replace Last Character of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "hello world";

str = str.substring(0, str.length - 1) + "x"; // replaces last character with 'x'

console.log(str); // outputs "hello worlx"

</script>

</html>

Example 2: Using slice and concatenation:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Replace Last Character of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "hello world";

str = str.slice(0, -1) + "x"; // replaces last character with 'x'

console.log(str); // outputs "hello worlx"

</script>

</html>

Example 3: Using substr and concatenation:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Replace Last Character of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "hello world";

str = str.substr(0, str.length - 1) + "x"; // replaces last character with 'x'

console.log(str); // outputs "hello worlx"

</script>

</html>

Example 4: Using regular expressions and replace method:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

<title>How to Replace Last Character of String in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = "hello world";

str = str.replace(/.$/, "x"); // replaces last character with 'x'

console.log(str); // outputs "hello worlx"

</script>

</html>

#JavaScript