2

This is for something else, but I put together an example to show this problem. Note: I want to remove all occurrences of "o", an coincidentally it seemed to look like i wanted to remove only the character at the end of the string - i thought there was a bug with not being able to remove the last character (and that replace replaced all occurrences).

var s = "hollo";
console.log(s);
s = s.replace("o", "");
console.log(s)

This happens on Chrome and Firefox which are the only browsers I've tested it with.

I get this in the console

hollo
hllo 

Why does it do this?

Edit: This seems to fix the problem:

if (s.lastIndexOf("o") != -1) s = s.substr(0, s.length - 1);

But I still want to know why exactly this happens.

Dylanthepiguy
  • 1,621
  • 18
  • 47

2 Answers2

5

That's because replace only removes the first match it sees. To remove all occurrences, use a regular expression instead. This one removes "o" globally (g) regardless of case (i).

s = s.replace(/o/gi,'');

Test this in the console and it should give you "hll":

'hollo'.replace(/o/gi,'');
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Can you add how to remove this character *at the end of the string*, as the OP's title states? – Jongware Apr 09 '14 at 09:32
  • @Jongware I think you missed the OP's point. He seems to want to remove all o's in the string, but can't remove the last one (the second one in fact) via `remove`. – Joseph Apr 09 '14 at 09:34
  • 1
    Ah right. The suggested "fix" at the end threw me off. – Jongware Apr 09 '14 at 09:35
  • (After futher rumination) The OP suggests "`replace` has a problem with the *last* character in a string". However, using the same input `hollo` and removing the `l` will show it's not related to the *position*. – Jongware Apr 09 '14 at 09:45
  • Joseph is right, replace(string, string) only removes the first occurrence. Note that firefox has an optional third argument for that case: replace(string, string, flags), where you can add "g" for global. This is not supported in chrome though. – ghost23 Apr 09 '14 at 09:49
0

I am undesratnd that you want to remove all 'o' from the string. You can also create prototy for same. you want to use like 's.ReplaceAll("o","")'.

function ReplaceAll(str,oldchar,newchar)
{

    if(str.indexOf(oldchar) != -1)
    {
        str = str.replace(oldchar, newchar);
        str = ReplaceAll(str,oldchar,newchar);
    }
    else
    {
        return str;
    }
}

var s = "hollo";
s = ReplaceAll(s,"o", "");

Let me know if i am not understand your requirement.

Jayesh Goyani
  • 11,008
  • 11
  • 30
  • 50