How can I remove a character from a string using JavaScript?

I am so close to getting this, but it just isn’t right. All I would like to do is remove the character r from a string. The problem is, there is more than one instance of r in the string. However, it is always the character at index 4 (so the 5th character).

Example string: crt/r2002_2

What I want: crt/2002_2

This replace function removes both r

mystring.replace(/r/g, '')

Produces: ct/2002_2

I tried this function:

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')

It only works if I replace it with another character. It will not simply remove it.

Any thoughts?

Leave a Comment