Reputation: 187
I am trying to use regex replace with a regex I have. When I use the match method it returns the array with the proper index and match but when I use replace and add the replace string it wouldnt work.
var a = "$#,##0.00".match("[\\d+-,#;()\\.]+");
console.log(a);
Returns ["#,##0.00", index: 1, input: "$#,##0.00"]
.
var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+","");
console.log(b);
Returns $#,##0.00
whereas I expect it to return just the $
Can someone point out what am I doing incorrectly? Thanks Link to the example is:
var a = "$#,##0.00".match("[\\d+-,#;()\\.]+");
console.log(a);
var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+","");
console.log(b);
Upvotes: 0
Views: 145
Reputation: 31682
.match
only accepts regexps. So if a string is provided .match
will explicitly convert it to a regexp using new RegExp
.
.replace
however accepts both a string (which will be taken literally as the search) or a regexp, you have to pass in a regexp if you want it to use a regexp.
var b = "$#,##0.00".replace(new RegExp("[\\d+-,#;()\\.]+"), "");
// ^^^^^^^^^^^ ^
or using a regexp literal:
var b = "$#,##0.00".replace(/[\d+-,#;()\.]+/, "");
Upvotes: 4