Home > Software design >  How to remove only www. part from a url - JavaScript
How to remove only www. part from a url - JavaScript

Time:09-06

I want to remove only the www. part from the URL in javascript. I have tried using the regex /^(?:www\.)?/i:

"www.example.com".replace(/^(?:www\.)?/i, "")

It works fine for the above example. But it doesn't work for URL starting with protocol like https://www.example.com.

Here's an example of what I'm trying to achieve:

https://www.example.com/   ->   https://example.com/

WWW.example.com/   ->   example.com/

CodePudding user response:

If you want to remove all instances of www, no matter where it appears

/www/.replace('')

If you explicitly want to ensure you are only removing 'www' when it comes after //

/(\/\/)www/.replace('$1')

just replace www if it comes before DOT

/www(\.)/.replace('$1')

Safest: To be sure you aren't remove www if it happens to sit in the querystring or hash

Caters for

  • www.
  • http://www.
  • //www.
/^([^:\.]*)(\:\/\/)?www(\.)/.replace('$1$2$3')

CodePudding user response:

Just replace keyword and fill with blanks
Example:
const urlMain = "https://www.example.com";
const endUrl = urlMain.replace("www.","");
console.log("Main Url",urlMain);
console.log("End Url",endUrl);
  • Related