user1584421
user1584421

Reputation: 3863

Node.js - Extracting part of the URL

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.

Upvotes: 4

Views: 2385

Answers (4)

fist ace
fist ace

Reputation: 47

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];

Upvotes: 2

Brad
Brad

Reputation: 163548

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

Upvotes: 2

Stephan Thierry
Stephan Thierry

Reputation: 101

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

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37775

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"))

Upvotes: 1

Related Questions