javascriptstr-replaceregex-negationmac-addressregexp-replace

Regex for Mac address not working properly


I am using javascript trying to grep everything that is NOT the mac address and remove it. Here is an example of a string.

var x = "20:ce:c4:00:01:e6 VLAN_ID=0";

I am trying to remove the "VLAN_ID=0" So the desired output would be:

var x ="20:ce:c4:00:01:e6"

I've used two different regexes for mac address:

const regex = /[0-9a-f]{1,2}([\\.:-])(?:[0-9a-f]{1,2}\1){4}[0-9a-f]+/;
const regex2 = /([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}\\.[0-9a-fA-F]{4}\\.[0-9a-fA-F]{4})+/;

I've tried playing around with the ^ but no luck Using x = x.replace(regex2, ""); It replaces everything that is the mac address leaving me with the output VLAN_ID=0


Solution

  • You can extract the result by accessing the first match like so:

    var x = "20:ce:c4:00:01:e6 VLAN_ID=0";
    const regex2 = /([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}\\.[0-9a-fA-F]{4}\\.[0-9a-fA-F]{4})+/;
    x = x.match(regex2)[0];
    console.log(x)