0

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);

2
  • You're passing a string to replace() ? Commented Apr 19, 2017 at 19:53
  • yes, an empty string as I just want $ as my result Commented Apr 19, 2017 at 19:54

1 Answer 1

4

.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+-,#;()\.]+/, "");
Sign up to request clarification or add additional context in comments.

5 Comments

ohh! I did not know that, I thought replace by default consumes a reg exp. Thanks for pointing that
+1 to answer, just pointing another possible way: var a = "$#,##0.00"; var b = a.replace(a.match("[\\d+-,#;()\\.]+"), ""); Also works, because a.match(...) will be a string
@GabrielMilitello The fastest way to get from USA to Japan is over the atlantic ocean, eh? :D.
@ibrahimmahrir :D just one thing, replace with "", not "a"... Think OP edited the question...
yeah, I edited it, that was a typo. Thanks @Gabriel for pointing another way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.