Languages
[Edit]
EN

JavaScript - replace last 2 characters in string

0 points
Created by:
FryerTuck
319

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

1. String slice() method example

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

// ONLINE-RUNNER:browser;

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

console.log(result); // ABxy

2. String substring() method example

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

// ONLINE-RUNNER:browser;

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

console.log(result); // ABxy

3. String replace() method example

There is another trick that allows to replace all characters that match rexpression condition with an empty string. By using .{0,2}$ pattern we match any 2 characters (up to 2 characters) that are loacated at the end of string. Then, we add the replacement at the end of the result string to replace the missing two characters.

// ONLINE-RUNNER:browser;

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

console.log(result); // ABxy

JavaScript - String (popular problems)

JavaScript - replace last 2 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