How to Replace the Last Character of a String in Javascript

Here’s a small program showing how to replace the last character of a String in Javascript.

Let us say we have a String stored in a variable called text:

let text = "ABC";

Here the last character of our String is “C”.

We want to change it with, let’s say, the character “M”.

We are going to take the help of Regular Expressions here.

We already have a method called replace that will come to the rescue.

So just type:

text.replace(

If you are using an IDE typing the above will automatically flare up the parameters this method uses etc.

So the first parameter needs to be what is being replaced, while the second one will be what it is being replaced with.

To use RegEx in Javascript, you must use the ‘/’ sign that signifies delimiter usage after which you can place your RegEx.

Put a ‘.’ after that.

. means any character.

and then a $ sign.

$ signifies the end of the String.

So our code would look like:

text.replace(/.$/

Notice how we have closed the delimiter with another ‘/’ forward slash to announce the end of RegEx. Now let’s enter the second parameter which is the character you want to replace it with.

text.replace(/.$/, 

Now use this code to replace the text with the letter M like this:

text.replace(/.$/, 'M')

That’s it!

The whole code would look like this:

let text = 'ABC';
console.log(text.replace(/.$/, 'M'));

Now if we run the above code we will get the result as:

ABM

Here’s a snapshot of the same program I have run on Visual Studio Code IDE.

how to replace the last character of a String in Javascript program

Similarly, if you want to mess with the beginning of the String the RegEx that you are going to need for that is ^

Go ahead and do this as homework on your own.

Please show me how to replace the first character of a string in Javascript.

Now, now…..go ahead. 🙂

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply