Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 886
Tufaaaaan Avatar asked Feb 26 '20 14:02

Tufaaaaan


People also ask

How do I format a MAC address in Excel?

Excel Format Mac Address 1 Select the cells you need to format as mac addresses. And then click Kutools > Text > Add Text. 2 In the Add Text dialog box, please type a colon into the Text box, select the Specify option, and then enter the... See More....

How do I format a MAC address string without delimiters?

To format a MAC address string without delimiters to a MAC address separated by a colon (:) or hyphen (-), you can use a formula based on the TEXTJOIN, MID, and SEQUENCE functions. In the example shown, the formula in D5, copied down, is: The formula returns the formatted strings as seen in column D.

How to easily format MAC addresses in cells by adding colon?

Easily format mac addresses in cells by adding colon with Kutools for Excel This section will introduce the Add Text utility of Kutoos for Excel. With this utility, you can quickly add colons to cells at specified positions. Please do as follows. Before applying Kutools for Excel, please download and install it firstly. 1.

Does excel for Mac - find and replace - no formatting option?

Excel for Mac - Find and Replace - No Formatting Option? I came here to ask the MS Community forum how to do a find-and-replace with formatting in Excel for Mac (for example, change the text color or highlight certain words throughout a lengthy document). What I have found, however, is that apparently Excel for Mac doesn't provide this option.


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);
like image 101
Josh Wulf Avatar answered Oct 08 '22 18:10

Josh Wulf