Borislav Hadzhiev
Mon Oct 11 2021·3 min read
Photo by Marko Horvat
To replace the first character in a string:
substring()
method, passing it 1
as a start index.+
operator, e.g.
a + str.substring(1)
.substring
method will return the part of the string from index 1
to
the end.const str = 'best'; const replaced = 't' + str.substring(1); console.log(replaced); // 👉️ test
In the example we replace the character b
with the character t
.
The only parameter we pass to the String.substring method is:
For our use case we want to exclude the first character in the string and prepend whatever we need.
0
and the last character an index of str.length - 1
.Note that the substring
method does not change the original string, it returns
a new string, containing the specified part of the original string.
This approach also works if you need to replace the first character with multiple characters.
const str = 'best'; const replaced = 'the t' + str.substring(1); console.log(replaced); // 👉️ the test
In the code snippet, we replace the character at index 0
, which is a b
with
the characters the t
.
An alternative approach is to use the replace
method.
To replace the first character in a string:
0
of the string to a variable.replace()
method passing it the variable as the first parameter
and the replacement character as the second, e.g. str.replace(char, 'a')
const str = 'best'; const char = str[0]; console.log(char); // 👉️ b const replaced = str.replace(char, 't'); console.log(replaced); // 👉️ test
The parameters we pass to the String.replace method are:
You will most commonly see the replace
method being passed a regular
expression as the first parameter, however we can also use a string for a
literal match.
By default the replace method replaces only the first match in the string, so it does exactly what we need.
replace
method does not mutate the original string, it returns a new string with one or more matches replaced. Strings are immutable in JavaScript.I prefer the first approach, because it is a bit easier to read and more direct.
Most developers have only used the replace
method with a regular expression
and not a string literal, so they might be surprised when they see it used like
that.