0

How can we shrink the URL in JavaScript:

for example if the link was like this, it should not extend after .com

https://stackoverflow.com/questions/ask

Expected Output:

https://stackoverflow.com

Thanks for your time,

Solution: I have used Regexp to shrink the url

const yourUrl = {your url goes here}  
const reConstructUrl = new RegExp(
      [
        "^(https?:)//", // protocol
        "(([^:/?#]*)(?::([0-9]+))?)", // host (hostname and port)
         '(/{0,1}[^?#]*)', // pathname
         '(\\?[^#]*|)', // search
         '(#.*|)$' // hash
      ].join("")
    )
const matchedUrl = yourUrl.match(reConstructUrl);

Now you can display only the part you want from the URL

Hari Haran
  • 33
  • 10
  • 1
    What have you tried so far? – AndrewL64 Mar 19 '21 at 05:18
  • I have tried shrinking using the length of the string and shrinking using letters but, if there is any way to shrink this using a string(like after .com) it could be better, or if you a have any suggestions I will try that also, – Hari Haran Mar 19 '21 at 05:22

2 Answers2

1

You can use the URL class to parse the URL and get the origin:

const url = new URL('https://stackoverflow.com/questions/ask');

console.log(url.origin);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

Based on this answer, you can do some thing like this

const url = new URL('https://stackoverflow.com/questions/ask');
console.log(url.origin)
majurageerthan
  • 2,169
  • 3
  • 17
  • 30