Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL string parameters?

I have this URL in my database, in the "location" field:

http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx

I can get it with @object.location, but how can I get the value of v? I mean, get "xxxxxxxxxxxx" from the URL string?

like image 282
el_quick Avatar asked Aug 23 '10 22:08

el_quick


People also ask

How do I find URL parameters?

Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.

What is parameter string in URL?

URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website. To identify a URL parameter, refer to the portion of the URL that comes after a question mark (?).

Is GET parameters are included in URL?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.


1 Answers

require 'uri'
require 'cgi'

# use URI.parse to parse the URL into its constituent parts - host, port, query string..
uri = URI.parse(@object.location)
# then use CGI.parse to parse the query string into a hash of names and values
uri_params = CGI.parse(uri.query)

uri_params['v'] # => ["xxxxxxxxxxxxxxxxxxx"]

Note that the return from CGI.parse is a Hash of Strings to Arrays so that it can handle multiple values for the same parameter name. For your example you would want uri_params['v'][0].

Also note that the Hash returned by CGI.parse will return [] if the requested key is not found, therefore uri_params['v'][0] will return either the value or nil if the URL did not contain a v parameter.

like image 135
mikej Avatar answered Oct 11 '22 17:10

mikej