In my node.js server i have a URL variable.
It is either in the form of ";, or "URL/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.
In my node.js server i have a URL variable.
It is either in the form of "https://www.URL./USEFUL_PART/blabla", or "URL./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.
Share Improve this question edited Jul 4, 2023 at 10:24 user1584421 asked Oct 5, 2019 at 18:00 user1584421user1584421 3,89312 gold badges57 silver badges98 bronze badges 3- 2 This is extremely mon in http framework routing, you could checkout express or hapi to see how they handle this :) – dm03514 Commented Oct 5, 2019 at 18:02
- I am using Express – user1584421 Commented Oct 5, 2019 at 18:03
- 2 Did u tried req.params? – Ilijanovic Commented Oct 5, 2019 at 18:06
4 Answers
Reset to default 2Since 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./en/api.html#req.params
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./", "");
str = str.split('/')[0];
In Node.js you can use "URL"
https://nodejs/docs/latest/api/url.html
const myURL = new URL('https://example/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz
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./USEFUL_PART/blabla"))
console.log(urlExtractor("URL./USEFUL_PART/blabla"))
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744937879a4602138.html
评论列表(0条)