jQuery addClass example
Change class name on click in jQuery
by ActualRandy
HTML
<h3 style="color:lawngreen">Replace Repeated Number with Roman Numeral via Regex</h3>
<a href="https://stackoverflow.com/questions/58493513/regex-how-can-i-convert-a-number-to-a-roman-form-if-the-number-is-repetitive">Refer to this StackOverflow question</a><br />
<label style="color:wheat">Input:</label>
<input type="text" id="txtInput" value="Hans4444mĂĽller,Mary555kren" />
<br />
<input type="button" id="btnRun" value="Run" />
<br />
<label style="color:aliceblue">Result:</label>
<input type="text" id="txtResult" />
CSS
body {
background: gray;
padding: 20px;
font-family: Helvetica;
}
JavaScript
$('#btnRun').click(function(){
var roman = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"];
//get the input text from the textbox:
var textToFix = $('#txtInput').val();
var result = "";
//regular expression matches repeated numbers, note the 'g' means global search
var re = /\d+/g;
var lastIndex = 0;
var lastMatch = "";
//get the first match:
var match = re.exec(textToFix);
while(match != null) {
var matchText = match[0];
//examine the 1st digit we matched and convert from text to number:
var number = matchText.charCodeAt(0) - 49;
//Use the number as an index into our array:
replaceText = roman[number];
var lastStop = lastIndex + lastMatch.length;
result += textToFix.substring(lastStop, match.index) + replaceText;
lastIndex = match.index;
lastMatch = match[0];
//Continue searching, get the next match:
match = re.exec(textToFix);
}
if (lastIndex > 0) {
var lastStop = lastIndex + lastMatch.length;
result += textToFix.substring(lastStop, textToFix.length);
}
$('#txtResult').val(result);
});