Search code examples
javascripthexdecimalregexp-replace

Javascript - Replace/convert more than 1 hexadecimal into decimal?


How can i replace some (more than one) hexadecimal into decimal? Which methods need to use?

Example text:

Try to convert this hex number 0x5A into (90) and 0x83 into (131).

I want to change that 0x54 and 0x83 in the text above into 90 and 131. I'm stuck and don't know which methods need to be used.

function convert() {
var code = document.getElementById("codearea").value;
var fhex = code.match(/0[xX][0-9a-fA-F]+/g);
for(var i=0; i<fhex.length;i++) fhex[i] = parseInt(fhex[i], 16);
var fhex1 = fhex;
var c = code.replace(/0[xX][0-9a-fA-F]+/g,fhex1)

document.getElementById("result").value = c;
}
<!-- TextArea Main -->
<textarea id="codearea" rows="5" cols="50">
Try to convert this hex number 0x5A into (90) and 0x83 into (131).
</textarea>
<div id="spacegap"></div>
<!-- TextArea Results -->
<textarea id="result" rows="5" cols="50">
</textarea>
</br>
<button id="btn" onclick="convert()">CLICK</button>


Solution

  • The reason you get both numbers twice in the output is because you passed fhex into replace, where it expected a string, so it converted [90, 131] into "90,131". Instead, you want to pass the converted number in, which then gets converted to the string you actually want.

    An additional problem is that if you pass the hexadecimal regex in as the first parameter to replace, then it will match all the hexadecimal numbers, so you want to pass something that only matches the string you want to replace with the number you currently have. Luckily, the string itself does that! So instead of replacing each fhex[i] value with a number, if you keep the string around, and put the number in a separate variable, you can pass the original string and the new number value into replace like so:

    function convert() {
    var code = document.getElementById("codearea").value;
    var fhex = code.match(/0[xX][0-9a-fA-F]+/g);
    for(var i=0; i<fhex.length;i++) {
        var number = parseInt(fhex[i], 16);
        code = code.replace(fhex[i], number)
    }    
    
    document.getElementById("result").value = code;
    }
    <!-- TextArea Main -->
    <textarea id="codearea" rows="5" cols="50">
    Try to convert this hex number 0x5A into (90) and 0x83 into (131).
    </textarea>
    <div id="spacegap"></div>
    <!-- TextArea Results -->
    <textarea id="result" rows="5" cols="50">
    </textarea>
    </br>
    <button id="btn" onclick="convert()">CLICK</button>