Languages
[Edit]
EN

JavaScript - replace last n characters in string

0 points
Created by:
maryam
251

In this article, we're going to have a look at how to replace last n 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 -n indexes as range we get <0, text.length - n> 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 n = 3;
let replacement = 'xyz';
let result = text.slice(0, -n) + replacement;

console.log(result); // Axyz

2. String substring() method example

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

// ONLINE-RUNNER:browser;

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

console.log(result); // Axyz

See also

  1. JavaScript - replace last character in string

  2. JavaScript - replace last 2 characters in string

  3. JavaScript - replace last 3 characters in string

  4. JavaScript - replace last 4 characters in string

JavaScript - String (popular problems)

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