I am trying to match
% in a string, say $ 3,222 and 100%.
In chrome dev tool,
If I do
+str.replace(/%|\$\s?|(,*)/g, ''). I get the correct result
But if I do a
+str.replace(/\$\s?|(,*)|%/g, ''), I get
Any reason for this peculiar behaviour?
const str = "$ 32,333%" console.log(+str.replace(/\$\s?|(,*)|%/g, '')) console.log(+str.replace(/%|\$\s?|(,*)/g, ''))
This doesn't directly answer your question (@Wiktor's answer does a good job with that), but it seems to me your goal is to get all the digits out of the string and toss the rest. An easier alternative is to use a negative character class to match for anything that is not a digit:
var str = "$ 32,333%"; var num = +str.replace(/[^0-9]/g,''); console.log(num); // 32333
String.prototype.replace(), The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. Syntax. const newStr = str .replace( regexp | substr , newSubstr | function ) F\b/g; return s.replace(test, convert); }� Syntax. The syntax to use the replace() method is as follows − string.replace(regexp/substr, newSubStr/function[, flags]); Argument Details. regexp − A RegExp object. The match is replaced by the return value of parameter #2.
const str = "$ 32,333%" console.log(+str.replace(/\D/g, ''))
- Yes, there is a reason:
,*matches an empty string. Use
- @WiktorStribiżew, How does
,*affect a match on