An alternative is to use split
to break the string into an array, and then use join
to generate a string again.
The parameter of split
is the separator (in case, -
). With this, an array will be generated with the parts of the address (00
, 25
, etc). And the parameter of the join
is the new separator (in case, :
), so the parts of the array will be joined into a single string, with the parts separated by :
. At last I used toLowerCase()
to make letters lower case:
let endereco = '00-25-66-F0-21-11';
let correto = endereco.split('-').join(':').toLowerCase();
console.log(correto); // 00:25:66:f0:21:11
Since you are only changing one character for another, I find this solution easier. But the solution from @Sorack with regex is also valid, and I would use it for more complex cases (when the separator is not just a single character, or it can be "any tiny character or digits", or any other criterion that is easier to do with regex).
Regarding the error of Object Undefined, it occurs because of the way you are trying to capture the value of input
and then set it back.
For example, call toString
is unnecessary because the value is already a string. And onmouseover
calls the conversion function when the mouse is placed over the field.
The right would be to convert the value only after the focus is removed from the field, and for that use 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>
and what’s wrong with your code? It’s not right??
– rLinhares
Is giving [Object Undefined]
– Anderson Fidelis
The
toString
is in the wrong place. Would:muda.mac.value.toString()
. Although you don’t even need to convert to string, since the value already seems to be a string. But the Sorack answer already said it all :D– Sam