Languages
[Edit]
EN

JavaScript - replace first 2 characters in string

0 points
Created by:
christa
600

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

Quick solution

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let result = 'xy' + text.slice(2);

console.log(result);  // xyCD

or:

// ONLINE-RUNNER:browser;

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

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

console.log(result);  // xyCD

or:

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let result = text.replace(/^.{2}/g, 'xy');

console.log(result);  // xyCD

 

1. Using string slice() with + operator

In this example, we use string slice() method to remove the first 2 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 replacer = 'xyz';

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

console.log(result);  // xyzCD

Note:

The replacer for the two removed characters may cosist of any number of characters, not only 2.

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

In this example, we use string slice() method to remove the first 2 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 replacer = 'xyz';

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

console.log(result);  // xyzCD

Note:

The replacer for the two removed characters may cosist of any number of characters, not only 2.

3. Using string replace() with regex

In this example, we use string replace() with /^.{2}/g regex to replace the first 2 characters in the text string.

Regex explanation:

  • ^ - matches the beginning of the string,
  • . - matches any character except linebreaks,
  • {2} - matches the specified quantity of the previous token (in our case the .).

Runnable example:

// ONLINE-RUNNER:browser;

let text = 'ABCD';
let result = text.replace(/^.{2}/g, 'xyz');

console.log(result);  // xyzCD

References

Alternative titles

  1. JavaScript - replace first two characters in string
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.

JavaScript - String (popular problems)

JavaScript - replace first 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