Replace ":" with "-" while also formatting mac address

Viewed 134

I'm currently using this to format an input text to have "-" after two characters and it replaces characters that are not "a-f" or "0-9" with "".

var macAddress = document.getElementById("macInput");

function formatMAC(e) {
  var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
      str = e.target.value.replace(/[^a-f0-9]/ig, "");

  while (r.test(str)) {
    str = str.replace(r, '$1' + '-' + '$2');
  }
  e.target.value = str.slice(0, 17);
};

macAddress.addEventListener("keyup", formatMAC, false);

I want it to also detect if the user writes ":" and replace it with "-", so it becomes impossible to write ":". Not sure how to accomplish this.

1 Answers

Easy. .split().join()

var macAddress = document.getElementById("macInput");

function formatMAC(e) {
  var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
      str = e.target.value.replace(/[^a-f0-9]/ig, "");

  while (r.test(str)) {
    str = str.replace(r, '$1' + '-' + '$2');
  }
  e.target.value = str.slice(0, 17).split(':').join('');
};

macAddress.addEventListener("keyup", formatMAC, false);
Related