1

Let's say my url atm is

http://test.com/?city=toronto

I'm able to get the requestURL string that is

/?city=toronto

From here, I was wondering if there is a built in function or a standard procedure of extracting the word "toronto" or any other word that comes after the = from the string.

user1692517
  • 1,122
  • 4
  • 14
  • 28

3 Answers3

4

A standard procedure (as you mentioned) of doing this, you can get all the parameter values including value of city or any other parameter you may add to it.

var values = new URL('http://test.com/?city=toronto').searchParams.values();
for(var value of values){
    console.log(value);
}

UPDATE

As @taystack mentioned in the comment, if you only want the value of a specific parameter (city) in this case, you can use:

new URL('http://test.com/?city=toronto').searchParams.get('city');
Faisal Umair
  • 381
  • 2
  • 5
0

Use split();

var url = '/?city=toronto'.split('=');
console.log(url[1]);
Asmarah
  • 134
  • 8
0

Node.js has a new module called URL, which encodes the semantics of a url string. You don’t need to do any string manipulation.

const URL = require('url')
let my_url = new URL('http://test.com/?city=toronto')

URL#search returns the string representing the search:

my_url.search // '?city=toronto'

URL#query returns the search string excluding ?:

my_url.query // 'city=toronto'

and URL#searchParams returns an object encoding the search string:

my_url.searchParams // something kind of like {'city':'toronto'}
my_url.searchParams.get('city') // 'toronto'
my_url.searchParams.keys() // ['city'] (all the keys)
my_url.searchParams.values() // ['toronto'] (all the values)
chharvey
  • 8,580
  • 9
  • 56
  • 95