Replace the first N characters in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 26, 2021

banner

Photo from Unsplash

Replace the first N characters in a String #

To replace the first N characters in a string, use the slice() method, passing it the number of characters you want to replace as a parameter and prepend the replacement string using the addition (+) operator.

index.js
const str = 'hello world'; const replaceFirst5 = 'test' + str.slice(5); console.log(replaceFirst5); // 👉️ 'test world' const replaceFirst2 = '__' + str.slice(2); console.log(replaceFirst2); // 👉️ __llo world

We used the String.slice method to get a substring containing the characters we want to keep.

The parameter we passed to the slice method is the start index - the index of the first character to be included in the new string.

The slice method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

The last step is to prepend the replacement string using the addition (+) operator.

To replace the first 3 characters of a string you would pass 3 as a parameter to the slice method to get a substring containing everything but the first 3 characters and add the replacement string at the front.

index.js
const str = 'hello world'; const replaceFirst3 = '...' + str.slice(3); console.log(replaceFirst3); // 👉️ ...lo world
Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0 and the index of the last - string.length - 1.

Because indexes are zero-based, an easy way to think about it is - the slice method takes the number of characters we want to cut from the string as a parameter.

Here are some more examples of using the slice method.

index.js
console.log('one two'.slice(3)); // 👉️ ' two' console.log('one two'.slice(4)); // 👉️ 'two' console.log('one two'.slice(5)); // 👉️ 'wo'

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.