Regular expression to isolate numbers from symbols and merge them as decimal numbers in JS

Viewed 57

I am trying to isolate specific format groups within strings and convert them through JS or jQuery and regex, strings like these

#aba #abc #33-25
#02-20 #abe #abf
#abg #abe #00-50 #aba
#aja #255-45

to these

33.25€
2.20€
0.50€
255.45€

.

1. In regex level, my workaround so far for isolating #xx.xx groups within strings is

s = "#aba #abc #33-25"
s.match( /(#[W\d-]+)/ )    //["#33-25", "#33-25"]

It recognize the #33-25 substring but outputs it 2 times in an array which is obviously insufficient.

.

2. Also how it will work (JS or jQuery) to (solved by @Kosh's answer)

  • remove # symbols
  • replace hyphen symbol (-) to dot symbol (.)
  • when #01-xx or #0-xx to convert to 1.xx or 0.xx (where x is obviously decimal numbers, always 2)
2 Answers

Use match and replace:

const convert = (s) => s
  .match(/#0*(0|[1-9]+)-(\d\d)\b/g)
  .map(m => m.replace(/#0*(0|[1-9]+)-(\d\d)/g, '$1.$2€'));

console.log(convert(`#aba #abc #33-25
#02-20 #abe #abf
#abg #abe #00-50 #aba
#aja #255-45`))

You can use

const texts = ['#aba #abc #33-25','#02-20 #abe #abf','#abg #abe #00-50 #aba','#aja #255-45'];
texts.forEach( x => {
  const m = x.match(/#(\d+)-(\d+)/);
  if (m) {
    console.log(x, '=>', `${m[1]}.${m[2]}€`);
  }
});

Here, x.match(/#(\d+)-(\d+)/) finds the first match of a /#(\d+)-(\d+)/ regex (# matches a # char, (\d+) captures one or more digits into Group 1, - matches a hyphen and (\d+) captures one or more digits into Group 2) in a string, and then ${m[1]}.${m[2]}€ builds the final result where m[1] is Group 1 and m[2] is Group 2 value.

Related