An alternative is to use split
to break the string in an array, and then use join
to generate a string again.
The parameter of split
is the separator (in this case, -
). This will generate an array with the parts of the address ( 00
, 25
, etc). And the join
parameter is the new separator (in this case, :
), so the parts of the array will be joined into a single string, with the parts separated by :
. Finally, I used toLowerCase()
to make the letters lowercase:
let endereco = '00-25-66-F0-21-11';
let correto = endereco.split('-').join(':').toLowerCase();
console.log(correto); // 00:25:66:f0:21:11
As you are only exchanging a single character for another, I find this solution easier. But the @Storack solution with regex is also valid, and I'd use it for more complex cases (when the is not just a single character, or it can be "any tiny character or digits", or any other criteria that is easier to do with regex).
As for the Object undefined error, it occurs because of the way you are trying to capture the value of input
and then set it back.
For example, calling toString
is unnecessary, since the value is already a string . E onmouseover
calls the conversion function when the mouse is placed on the field.
The right thing would be to convert the value only after the focus is taken from the field, and for this onblur
.
The corrected code looks like this:
function capturamac(){
var macadd = muda.mac.value;
var corrige = macadd.split('-').join(':').toLowerCase();
muda.mac.value = corrige;
}
<html>
<form name="muda">MAC: <input type="text" name="mac" id="macad" onblur="capturamac()" /></form>
</html>