Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all instances of a character from a string

I'm attempting to remove all instances of a given set of characters £$€,. from a string in jQuery/Javascript. I'm using the replace function, however this only appears to remove a single instance of the character and not all of them.

For example consider the string:

1,500,00.00.$djdjd£10€10

I get back:

1500,0000.djdjd1010

As you can see, it only removes a single instance of each character. £, $ and are fine as there is only one of each in the string.

Here is what I have so far:

function validatePriceRange(value, min, max) {

    var replacements = ["£", "$", "€", ",", "."];

    $.each(replacements, function (index, item) {
        value = value.replace(item, "");
    });

    var value = parseInt(value, 10);

    return value >= min && value <= max;
}

jsFiddle

Can anyone spot what I've done wrong?

like image 759
DGibbs Avatar asked Sep 15 '25 11:09

DGibbs


1 Answers

replace called with a string as first argument does only one replacement, while using a regular expression with flag g replaces all occurrences.

Using a regular expression, you can also avoid looping over an array and do it in one pass :

value = value.replace(/£|\$|€|,|\./g,'');
like image 99
Denys Séguret Avatar answered Sep 17 '25 00:09

Denys Séguret