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

var mystring = "crt/r2002_2";
mystring = mystring.replace('/r',"https://stackoverflow.com/");

will replace /r with / using String.prototype.replace.

Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with

mystring = mystring.replace(/\/r/g, "https://stackoverflow.com/");

EDIT:
Since everyone’s having so much fun here and user1293504 doesn’t seem to be coming back any time soon to answer clarifying questions, here’s a method to remove the Nth character from a string:

String.prototype.removeCharAt = function (i) {
    var tmp = this.split(''); // convert to an array
    tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
    return tmp.join(''); // reconstruct the string
}

console.log("crt/r2002_2".removeCharAt(4));

Since user1293504 used the normal count instead of a zero-indexed count, we’ve got to remove 1 from the index, if you wish to use this to replicate how charAt works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1) instead.

Leave a Comment