Languages
[Edit]
EN

JavaScript - replace first n characters in string

0 points
Created by:
Admin Dirask Community
1420

In this article, we would like to show you how to replace the first n characters in string in JavaScript.

Quick solution

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let n = 3;
let result = 'xyz' + text.slice(n);

console.log(result);  // xyzD

or:

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let n = 3;
let replacer = 'xyz';

let result = replacer.concat(text.slice(n));

console.log(result);  // xyzD

 

1. Using string slice() with + operator

In this example, we use string slice() method to remove the first n characters of the text string. Then with + operator we add the remainder of the text to the replacer.

Runnable example:

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let n = 3;
let replacer = 'xy';

let result = replacer + text.slice(n);

console.log(result);  // xyD

Note:

The replacer for the n removed characters may cosist of any number of characters, not exactly n.

2. Using string slice() with concat() method

In this example, we use string slice() method to remove the first n characters of the text string. Then with concat() method we add the remainder of the text to the replacer.

Runnable example:

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let n = 3;
let replacer = 'xy';

let result = replacer.concat(text.slice(n));

console.log(result);  // xyD

Note:

The replacer for the n removed characters may cosist of any number of characters, not exactly n.

References

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