Advertisement
ZeroSeventty

Extract decimal fron string regex

Apr 11th, 2022
1,357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const regex = /[0-9][+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?/g;
  2.  
  3. // Alternative syntax using RegExp constructor
  4. // const regex = new RegExp('[0-9][+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\\.[0-9]{2})?', 'g')
  5.  
  6. const str = `\$20,000.00 USD`;
  7. let m;
  8.  
  9. while ((m = regex.exec(str)) !== null) {
  10.     // This is necessary to avoid infinite loops with zero-width matches
  11.     if (m.index === regex.lastIndex) {
  12.         regex.lastIndex++;
  13.     }
  14.    
  15.     // The result can be accessed through the `m`-variable.
  16.     m.forEach((match, groupIndex) => {
  17.         console.log(`Found match, group ${groupIndex}: ${match}`);
  18.     });
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement