4

In my node.js server i have a URL variable.

It is either in the form of "https://www.URL.com/USEFUL_PART/blabla", or "URL.com/USEFUL_PART/blabla".

From this, i want to extract only the 'USEFUL_PART' information.

How do i do that with Javascript?

I know there are two ways to do this, one with vanilla js and one with regular expressions. I searched the web but i only found SO solutions to specific questions. Unfortunately, i coulnd't find a generic tutorial i could replicate or work out my solution.

3
  • 2
    This is extremely common in http framework routing, you could checkout express or hapi to see how they handle this :) Commented Oct 5, 2019 at 18:02
  • I am using Express Commented Oct 5, 2019 at 18:03
  • 2
    Did u tried req.params? Commented Oct 5, 2019 at 18:06

4 Answers 4

2

Since you're using Express, you can specify the part of the URL you want as parameters, like so:

app.get('/:id/blabla', (req, res, next) => {
  console.log(req.params); // Will be { id: 'some ID from the URL']
});

See also: https://expressjs.com/en/api.html#req.params

Sign up to request clarification or add additional context in comments.

Comments

2

Hey if you are using express then you can do something like this

app.get('/users/:id/blabla',function(req, res, next){
   console.log(req.params.id);
 }

Another way is to use javascript replace and split function

str = str.replace("https://www.URL.com/", "");
str = str.split('/')[0];

Comments

1

In Node.js you can use "URL"
https://nodejs.org/docs/latest/api/url.html

const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz

Comments

1

One way is to check whether the url starts with http or https, if not then manually add http, parse the url using the URL api, take the patname from parsed url, and get the desired part

let urlExtractor = (url) =>{
  if(!/^https?:\/\//i.test(url)){
    url = "http://" + url
  }
  let parsed = new URL(url)
  return parsed.pathname.split('/')[1]
}

console.log(urlExtractor("https://www.URL.com/USEFUL_PART/blabla"))
console.log(urlExtractor("URL.com/USEFUL_PART/blabla"))

2 Comments

If it doesn't contain ('http' OR 'https') it will add 'http' OK. But what if it contains 'http'? Will this code put an 'https' before it?
@user1584421 no it will add only when the http or https is missing at start

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.