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?
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.
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 (?).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With