Languages
[Edit]
EN

JavaScript - replace last 3 characters in string

0 points
Created by:
Jacob
532

In this article, we're going to have a look at how to replace the last 3 characters from string in JavaScript.

1. String slice() method example

This approach allows getting substring by using negative indexes. So by using 0 and -3 indexes as the range we get <0, text.length - 3> text range. Then, we add the replacement at the end of the result string to replace the missing three characters.

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let replacement = 'xyz';
let result = text.slice(0, -3) + replacement;

console.log(result); // Axyz

2. String substring() method example

This is an alternative approach to slice method based solution. We remove the last 3 characters to add the replacement at the end of the result string to replace the missing three characters.

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let replacement = 'xyz';
let result = text.substring(0, text.length - 3) + replacement;

console.log(result); // Axyz

3. String replace() method example

There is another trick that allows replacing all characters that match expression conditions with an empty string. By using .{0,3}$ pattern we match any 3 characters (up to 3 characters) that are located at the end of the string. Then, we add the replacement at the end of the result string to replace the missing three characters.

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let replacement = 'xyz';
let result = text.replace(/.{0,3}$/, '') + replacement;

console.log(result); // Axyz
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - replace last 3 characters in string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join