简体   繁体   中英

javascript regex match works but replace doesnt work

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

.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+-,#;()\.]+/, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM