517

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
user1293504
  • 5,211
  • 2
  • 15
  • 6

22 Answers22

647
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.

JKirchartz
  • 17,612
  • 7
  • 60
  • 88
103

A simple functional javascript way would be

mystring = mystring.split('/r').join('/')

simple, fast, it replace globally and no need for functions or prototypes

Strife86
  • 1,135
  • 1
  • 10
  • 18
  • 3
    It works great for me. While i try mystring = mystring.replace('/r','/'); it only converts the first corrector, rest of them are as it is. – VishnuPrasad Aug 21 '15 at 05:16
  • 2
    The fourth character is not necessarily a `'/'` – jak.b Jan 12 '19 at 15:19
  • 1
    anyway according to tests (https://stackoverflow.com/questions/50463850/split-and-join-function-or-the-replace-function) unless youre writting a high performance (10k operations per sec) javascript the performance difference is not an issue or "high price to pay" so i dont see how exactly your comment contribute to the solution – Strife86 May 27 '19 at 17:01
  • 1
    Aside from being inefficient (and a function like this may be used iteratively on long lists where it matters) this doesn't answer the OP's question which depends on index, not on the preceding character. – aamarks Jul 22 '19 at 17:39
76

There's always the string functions, if you know you're always going to remove the fourth character:

str.slice(0, 4) + str.slice(5, str.length)
Harshay Buradkar
  • 3,493
  • 2
  • 15
  • 19
simpleigh
  • 2,854
  • 18
  • 19
  • This does not work when removing first or last character – TekTimmy Mar 15 '18 at 09:39
  • 4
    @TekTimmy Why not? `str.slice(0, 0) + str.slice(1, str.length)` removes the first and `str.slice(0, str.length-1) + str.slice(str.length, str.length)` removes the last. (Of course you would remove the redundant parts if you know you're always removing the first or last, but if they're variables they work just as well as any other index.) – JJJ Nov 17 '18 at 14:14
  • 2
    There's an extra `)` at the end. – Srishti Gupta Mar 15 '21 at 13:14
34

Your first func is almost right. Just remove the 'g' flag which stands for 'global' (edit) and give it some context to spot the second 'r'.

Edit: didn't see it was the second 'r' before so added the '/'. Needs \/ to escape the '/' when using a regEx arg. Thanks for the upvotes but I was wrong so I'll fix and add more detail for people interested in understanding the basics of regEx better but this would work:

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

Now for the excessive explanation:

When reading/writing a regEx pattern think in terms of: <a character or set of charcters> followed by <a character or set of charcters> followed by <...

In regEx <a character or set of charcters> could be one at a time:

/each char in this pattern/

So read as e, followed by a, followed by c, etc...

Or a single <a character or set of charcters> could be characters described by a character class:

/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)

Or expanded on to match a quantity of characters (but still best to think of as a single element in terms of the sequential pattern):

/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would

/[aA]{1,3}/
//1-3 matches of 'a' or 'A'

/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class

/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)

So smoosh a bunch together:

   var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
   var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can   eat098765';

   joesStr.match(rePattern);

   //returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
   //without the 'g' after the closing '/' it would just stop at the first   match and return:
   //["aaaAAAaaEat at Joes123454321"]

And of course I've over-elaborated but my point was simply that this:

/cat/

is a series of 3 pattern elements (a thing followed by a thing followed by a thing).

And so is this:

/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/

As wacky as regEx starts to look, it all breaks down to series of things (potentially multi-character things) following each other sequentially. Kind of a basic point but one that took me a while to get past so I've gone overboard explaining it here as I think it's one that would help the OP and others new to regEx understand what's going on. The key to reading/writing regEx is breaking it down into those pieces.

neophyte
  • 6,540
  • 2
  • 28
  • 43
Erik Reppen
  • 4,605
  • 1
  • 22
  • 26
19

Just fix your replaceAt:

String.prototype.replaceAt = function(index, charcount) {
  return this.substr(0, index) + this.substr(index + charcount);
}

mystring.replaceAt(4, 1);

I'd call it removeAt instead. :)

Ken White
  • 123,280
  • 14
  • 225
  • 444
16

For global replacement of '/r', this code worked for me.

mystring = mystring.replace(/\/r/g,'');
Sagar Gala
  • 944
  • 10
  • 10
11

This is improvement of simpleigh answer (omit length)

s.slice(0, 4) + s.slice(5)

let s = "crt/r2002_2";
let o = s.slice(0, 4) + s.slice(5);
let delAtIdx = (s, i) => s.slice(0, i) + s.slice(i + 1); // this function remove letter at index i

console.log(o);
console.log(delAtIdx(s, 4));
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • This is the most straight-forward when paired with `.substring(start,end)` to get a substring, then remove the substring. – franklylately Mar 19 '22 at 22:12
8

let str = '1234567';
let index = 3;
str = str.substring(0, index) + str.substring(index + 1);
console.log(str) // 123567 - number "4" under index "3" is removed
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Nazariy
  • 408
  • 3
  • 10
7
return this.substr(0, index) + char + this.substr(index + char.length);

char.length is zero. You need to add 1 in this case in order to skip character.

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
  • This doesn't answer the question asked; it simply explains why `replaceAt` isn't working. It should be a comment to the original question instead of an answer. :) – Ken White Mar 29 '12 at 20:31
  • @KenWhite, infact it does answer the only question ask, `Any thoughts?`. – Ash Burlaczenko Mar 29 '12 at 20:33
  • Fair enough. I don't agree, but... :) I didn't downvote, but I don't think it qualifies as an answer. An answer would provide a solution to the problem, or at least explain with more detail and offer an idea of how to fix it. – Ken White Mar 29 '12 at 20:38
  • @KenWhite, I agree, I was just making the point that the OP could of made his question clearer? Some people only want pointing in a direction rather than just given the answer. – Ash Burlaczenko Mar 29 '12 at 20:41
  • 1
    +1 for @paislee - this answer isn't helpful 'cause there is no such thing as a char in JavaScript. – simpleigh Mar 29 '12 at 20:52
  • `char` is the OP's parameter name! This answer solves the problem: using 1 instead of char.length. The OP's function is badly written originally because the OP always wanted to remove one character at the index. It should never have had the replacement.length as a factor on where to start the kept tail string. – aamarks Jul 22 '19 at 17:50
6

Maybe I'm a noob, but I came across these today and they all seem unnecessarily complicated.

Here's a simpler (to me) approach to removing whatever you want from a string.

function removeForbiddenCharacters(input) {
let forbiddenChars = ['/', '?', '&','=','.','"']

for (let char of forbiddenChars){
    input = input.split(char).join('');
}
return input

}

Matt S
  • 249
  • 2
  • 8
  • 1
    While you may think this solution is simpler and the others are "unnecessarily complicated" this solution has poor runtime performance due to the repeated string splitting and joining (which will incur excessive amounts of new string allocations and copying). I compared your solution to a single `.replaceAll` call in this benchmark ( https://jsben.ch/AAGDc ) and `replaceAll` is 96% faster. – Dai Jul 09 '22 at 09:36
5

Create function like below

  String.prototype.replaceAt = function (index, char) {
      if(char=='') {
          return this.slice(0,index)+this.substr(index+1 + char.length);
      } else {
          return this.substr(0, index) + char + this.substr(index + char.length);
      }
  }

To replace give character like below

  var a="12346";
  a.replaceAt(4,'5');

enter image description here

and to remove character at definite index, give second parameter as empty string

a.replaceAt(4,'');

enter image description here

ata
  • 3,398
  • 5
  • 20
  • 31
Rajiv
  • 1,245
  • 14
  • 28
3

You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)

Explanation:

  1. if ( str[4] === 'r' )
    Check if the 5th character is a 'r'

  2. str.slice(0, 4)
    Slice the string to get everything before the 'r'

  3. + str.slice(5)
    Add the rest of the string.

Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]

DEMO:

function remove5thR (s) {
  s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;
  console.log(s); // log output
}

remove5thR('crt/r2002_2')  // > 'crt/2002_2'
remove5thR('crt|r2002_2')  // > 'crt|2002_2'
remove5thR('rrrrr')        // > 'rrrr'
remove5thR('RRRRR')        // > 'RRRRR' (no change)
jak.b
  • 273
  • 4
  • 15
3

If you just want to remove single character and If you know index of a character you want to remove, you can use following function:

/**
 * Remove single character at particular index from string
 * @param {*} index index of character you want to remove
 * @param {*} str string from which character should be removed
 */
function removeCharAtIndex(index, str) {
    var maxIndex=index==0?0:index;
    return str.substring(0, maxIndex) + str.substring(index, str.length)
}
dd619
  • 5,910
  • 8
  • 35
  • 60
3

If it is always the 4th char in yourString you can try:

yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });
Just_Mad
  • 4,029
  • 3
  • 22
  • 30
3

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

This is because when char is equal to "", char.length is 0, so your substrings combine to form the original string. Going with your code attempt, the following will work:

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + 1);
    //   this will 'replace' the character at index with char ^
}
calebds
  • 25,670
  • 9
  • 46
  • 74
2

I dislike using replace function to remove characters from string. This is not logical to do it like that. Usually I program in C# (Sharp), and whenever I want to remove characters from string, I use the Remove method of the String class, but no Replace method, even though it exists, because when I am about to remove, I remove, no replace. This is logical!

In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

and then you can use these two functions or one of them for your needs!

Example:

alert(Remove("crt/r2002_2", 4, 1));

Output: crt/2002_2

Achieving goals by doing techniques with no logic might cause confusions in understanding of the code, and future mistakes, if you do this a lot in a large project!

  • 3
    I'd say that introducing extraneous methods is much more confusing that just using `String.prototype.replace`, which is a part of the base API. Moreover, understanding removal as a special case of replacement is fairly logical as far as programming goes. You shouldn't be trying to make your API comprise all the words in the English dictionary, you should try to reduce your API to its minimal orthogonal base. – Witiko May 01 '15 at 19:30
2

The following function worked best for my case:

public static cut(value: string, cutStart: number, cutEnd: number): string {
    return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}
TekTimmy
  • 3,066
  • 2
  • 29
  • 33
2

The shortest way would be to use splice

var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);
Gabriel Stellini
  • 426
  • 4
  • 13
  • [Splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) mutates the original array and returns only the elements effected. Since arrays are zero-indexed, this example will return "" (since the 3rd element in the array is the blank between the `c` and the `"`) – JKirchartz Sep 12 '19 at 16:46
2

This problem has many applications. Tweaking @simpleigh solution to make it more copy/paste friendly:

function removeAt( str1, idx) {
  return str1.substr(0, idx) + str1.substr(idx+1)
}
console.log(removeAt('abbcdef', 1))  // prints: abcdef
Babar-Baig
  • 689
  • 1
  • 12
  • 25
1

Using [index] position for removing a specific char (s)

String.prototype.remplaceAt = function (index, distance) {
  return this.slice(0, index) + this.slice(index + distance, this.length);
};

credit to https://stackoverflow.com/users/62576/ken-white

Daniel
  • 373
  • 4
  • 10
0

So basically, another way would be to:

  1. Convert the string to an array using Array.from() method.
  2. Loop through the array and delete all r letters except for the one with index 1.
  3. Convert array back to a string.

let arr = Array.from("crt/r2002_2");

arr.forEach((letter, i) => { if(letter === 'r' && i !== 1) arr[i] = "" });

document.write(arr.join(""));
Gass
  • 7,536
  • 3
  • 37
  • 41
-2

In C# (Sharp), you can make an empty character as '\0'. Maybe you can do this:

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

Search on google or surf on the interent and check if javascript allows you to make empty characters, like C# does. If yes, then learn how to do it, and maybe the replaceAt function will work at last, and you'll achieve what you want!

Finally that 'r' character will be removed!