1

I want to replace certain strings (roman numbers) in a string with nodejs.

A simple concatenation of .replace() is not working as expected, because obviously some roman numbers are contained with other roman numbers. That sounds awful, but this example explains:

"III".replace('I', '1'); 
// "111";

offcourse we can reorder the .replace() methods to surpress this behaviour, like so:

"III".replace('III', '3').replace('II', '2').replace('I', '1'); 
// "3"

But then with XI we get into trouble.
Is there a smarter way to do this?

stUrb
  • 6,612
  • 8
  • 43
  • 71
  • While [this question](http://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript#9083037) isn't quite a duplicate - it looks the wrong way round on the face of it - it does have an answer that provides conversions in both directions – James Thorpe Nov 27 '14 at 15:33
  • Don't use regexps to parse Roman numerals. Just write a little mini-parser. –  Nov 27 '14 at 16:47

1 Answers1

0

Of course. You have to add the numbers. For example:

"111" could be 1+1+1 = 3

You have to be sure that sometimes an small number on the left of a bigger number should substract in the final number. So if you validate that it's really easy.

For example:

"IV" = 4
I = 1
V = 5

I<V

So, the result will be:

5-1 = 4

The number 1 should be substracted because is on the left of a bigger number.