Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 486
user1293504 Avatar asked Mar 29 '12 20:03

user1293504


People also ask

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you cut a character in JavaScript?

To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 1) .

How do you remove all characters from a string after a specific character in JavaScript?

What is this? Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str.


1 Answers

var mystring = "crt/r2002_2"; mystring = mystring.replace('/r','/'); 

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, '/'); 

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.

like image 101
JKirchartz Avatar answered Oct 03 '22 03:10

JKirchartz