Search code examples
javascriptregexalertconfirm

How to remove a pattern in JS Regex?


The following code hides all webpages of a certain website and mocks the website.

let sites = ['mako.co.il', 'walla.co.il'];

for (let i = 0; i < sites.length; i++) {
    if (window.location.href.indexOf(sites[i]) != -1 ) {

    alert(` Enough with this ${sites[i]} garbage! `);
    }
}

It displays domain.tld this way:

"Enough with this domain.tld garbage!".

How could I strip away the .tld, so the final outcome would be:

"Enough with this domain garbage!".

A /[domain]@.2,/ regex might unmatch tld's like .com or co.uk and only "domain" will appear on the alert, but I don't know how to implement such regex to the sites[i] in the confirm.

Do you know?


Solution

  • It depends how complex your strings can get, but a simple match for domains could be something as follows:

    str.replace(/(\.[a-zA-Z]{1,3}){1,2}/, '')
    

    This will work for most examples of "domain.com", "domain.co.uk", "domain.es". You might be able to find a better regex, but the idea would be the same.