Home > Enterprise >  jQuery - Find MAC in string and optionally format it
jQuery - Find MAC in string and optionally format it

Time:07-15

I have a field on my site that allows the user to enter data. Often within that they will include a MAC address.

I need a way to find the MAC address within the string and if it is a delimited format offer to reformat it for them and then update the string.

As I see it there are four things to do here:

  1. With in string find MAC address delimited with : or - eg: 00:12:34:56:78:90 or 00-12-34-56-78-90 and return this as a var.
  2. If var exists show a confirm box asking them if they want it formatting. I can do this is the var is there.
  3. If they confirm reformat MAC removing delimiter - I think I can do.
  4. Update string with new MAC address - this I'm assuming is a simple find of old var and replace with new var.

For example:

The user enters 'This is a string containing 00:12:34:56:78:90 within it.' I need to find 00:12:34:56:78:90 show confirm, change MAC to 001234567890 and update string so it reads:

'This is a string containing 001234567890 within it.'

The MAC can appear anywhere in the string, start middle or end and may have whitespace around it. The delimiter will be : or -

Does anyone have any ideas how I can do this, specifically step 1 ?

Thanks

CodePudding user response:

Regex used from : What is a regular expression for a MAC Address?
Slightly modified to match the MAC Address present at any position

let macRegex = /([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})/g;
let text = 'My Wifi MAC Address is 2C:54:91:88:C9:E3 and my bluetooth MAC Address is 3D-F2-C9-A6-B3-4F';
let macPresent = macRegex.test(text);
let getMac = text.match(macRegex);

let colonOrHypenRegex = /[:-]/g;
let firstMacReplaced = getMac[0].replaceAll(colonOrHypenRegex, '');
console.log({macPresent, getMac, firstMacReplaced})

  • Related