0

I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click. How can I replace only the whole numbers and not parts of the other numbers. For example, I have:

XI
XXI
XXXI

and I get

11
X11
XX11

but I want

11
XXI
XXXI

The code I'm using is:

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5" 
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}

I've seen various solutions with using \b but I can't figure out where to put it in my code. Thanks.

user3080392
  • 1,194
  • 5
  • 18
  • 35

3 Answers3

2

I took your spec and made it "work", by:

  • Defining the correct regular expression \b[XIV]+\b (matches a whole roman number)
  • Use your object as a mapping function and a fallback if it fails, mapObj[roman] || roman

What the script doesn't do:

  • Catch illegal roman numbers, i.e. it allows XIIX
  • Implement a proper algorithm for the match, like XV, idealistically should parse to 10 + 5 = 15

function fromRoman(roman) {
  var mapObj = {
    XI:"11",
    V:"5" 
  };
  return mapObj[roman] || roman;
}

function convertFromRoman() {
  var str = document.getElementById("textArea").value;
  var output = str.replace(/\b[XIV]+\b/g, fromRoman);
  document.getElementById("output").value = output;
}

convertFromRoman();
<p>Input:</p>

<textarea id="textArea" style="width:100%; height:50px" onkeyup="convertFromRoman()">
XI
XXI
XXXI
</textarea>

<p/>

<p>Output:</p>

<textarea id="output" style="width:100%; height:50px">
</textarea>
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
1

What you need is add \\b to begin and end of the regular expression. It will match the whole word.

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5" 
  };

  var re = new RegExp("\\b(" + Object.keys(mapObj).join("|") + ")\\b","gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}
<textarea id="textArea" style="width: 400px; height: 100px"></textarea>
<br />
<button onClick="romanToArabic()">Convert</button>
Daniel Tran
  • 6,083
  • 12
  • 25
0

Here is another way , just split your textArea value by new line ('\n').

var val=["XI", "XXI", "XXXI"]; // $("textarea").val().split('\n');
var outPut = [];
$.each(val, function(index, object) {
 if(object.length == 2){
   outPut.push(object.replace("XI",'11'));
 }else{
    outPut.push(object);
}
 console.log(outPut[outPut.length-1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
manikant gautam
  • 3,521
  • 1
  • 17
  • 27