0

I'm aware that you can get the query string of a URL like:

var url = require("url");

...

http.createServer((req,res) => console.log(url.parse(req.url).query))

But that's only if the variables are in a query-string format:

example.com/index.html?key=val&key2=val2

etc...

But what if I wanted to get the "variables" in the form of values if the url was in a format:

example.com/key/val/key2/val2

?

I could just split the array for /'s and then map it accordingly:

var pathParts = request.url.split("/").filter(x => x.length > 0).map(x => x.split("%20").join(" "));

but that would fail for a URL like this:

example.com/url/http://google.com

So how can I get each of the values separated by / as a unique array element, even if there are nested /'s ?

3
  • You should urlencode your strings anyway, that way it would be example.com/url/http%3A%2F%2Fgoogle.com Commented Mar 13, 2019 at 9:53
  • @MichałSadowski Oh cool, how do I do that? (and then decode?) Commented Mar 13, 2019 at 9:55
  • @MichałSadowski I realized about the encodeURIComponent and decodeUriComponent, but I realized it still doesn't help me: because I need to separate each value by one / at a time, how can I separate example.com/key/http: //yahoo.com/key2/http: //google.com (without the spaces) Commented Mar 13, 2019 at 10:00

1 Answer 1

1

First, when you create a url you need to encode every part of it using encodeURIComponent(). This way you will get an url that is, for example: example.com/url1/http%3A%2F%2Fgoogle.com/url2/http%3A%2F%2Fbing.com. Then reading it back is as simple as using:

let requestArray = request.url.split("/")
let requestDecodedArray = requestArray.map((el)=>decodeURIComponent(el))
Sign up to request clarification or add additional context in comments.

5 Comments

When I run encodeURIComponent on a string like this question: (take out space after "https "): encodeURIComponent("https ://stackoverflow.com/questions/55138803/node-js-javascript-get-all-parts-of-url-parth-hierchy/55139317#55139317") it encodes every "/" and doesn't differentiate between them at all, try it in the console
@bluejayke that's why you need to run it before composing the url, on every part of it, instead on it whole.
How should I do that, the user is the one who inputs the URL to their browser and I get it from request.url
Users generally don't input URL directly, but get it, for example, from links; otherwise you would never know what kind of input you will get. You need to solve it from UI perspective, but I bet it's gonna be done during link href composing.
I want to just use the URL as a variable

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.