Languages
[Edit]
EN

JavaScript - replace first character in string

3 points
Created by:
Maison-Humphries
791

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

Quick solution

// ONLINE-RUNNER:browser;

let text = 'ABC';
let result = 'x' + text.slice(1);

console.log(result);  // xBC

or:

// ONLINE-RUNNER:browser;

let text = 'ABC';
let replacer = 'x';

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

console.log(result);  // xBC

or:

// ONLINE-RUNNER:browser;

let text = 'ABC';
let result = text.replace(/^./g, 'x');

console.log(result);  // xBC

 

1. Using string slice() with + operator

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

Runnable example:

// ONLINE-RUNNER:browser;

let text = 'ABC';
let replacer = 'x';

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

console.log(result);  // xBC

Note:

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

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

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

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

console.log(result);  // xBC

Note:

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

3. Using string replace() with regex

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

Regex explanation:

  • ^ - matches the beginning of the string,
  • . - matches any character except linebreaks.

Runnable example:

// ONLINE-RUNNER:browser;

let text = 'ABC'
let result = text.replace(/^./g, 'x');

console.log(result);  // xBC

References

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 character 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