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?
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,'');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With