Last updated: Oct 26, 2021
Photo from Unsplash
To replace the first N characters in a string, use the
passing it the number of characters you want to replace as a parameter and
prepend the replacement string using the addition (+) operator.
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 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
slice method to get a substring containing everything but the first 3
characters and add the replacement string at the front.
const str = 'hello world'; const replaceFirst3 = '...' + str.slice(3); console.log(replaceFirst3); // 👉️ ...lo world
0and the index of the last -
string.length - 1.
Because indexes are zero-based, an easy way to think about it is - the
method takes the number of characters we want to cut from the string as a
Here are some more examples of using the
console.log('one two'.slice(3)); // 👉️ ' two' console.log('one two'.slice(4)); // 👉️ 'two' console.log('one two'.slice(5)); // 👉️ 'wo'