Replace the first N characters in a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Lucija Ros

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee