7

I have a bunch of URLs which I would like to clean. They all contain UTM parameters, which are not necessary, or rather harmful in this case. Example:

http://houseofbuttons.tumblr.com/post/22326009438?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+HouseOfButtons+%28House+of+Buttons%29

All potential parameters begin with utm_. How can I remove them easily with a ruby script / structure without destroying other potentialy "good" URL parameters?

2 Answers 2

12

You can apply a regex to the urls to clean them up. Something like this should do the trick:

url = 'http://houseofbuttons.tumblr.com/post/22326009438?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+HouseOfButtons+%28House+of+Buttons%29&normal_param=1'
url.gsub(/&?utm_.+?(&|$)/, '') => "http://houseofbuttons.tumblr.com/post/22326009438?normal_param=1"
11

This uses the URI lib to deconstruct and change the querystring (no regex):

require 'uri'
str ='http://houseofbuttons.tumblr.com/post/22326009438?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+HouseOfButtons+%28House+of+Buttons%29&normal_param=1'

uri = URI.parse(str)
clean_key_vals = URI.decode_www_form(uri.query).reject{|k, _| k.start_with?('utm_')}
uri.query = URI.encode_www_form(clean_key_vals)
p uri.to_s #=> "http://houseofbuttons.tumblr.com/post/22326009438?normal_param=1"
5
  • @steenslag Mine is a tiny standalone script. It gives me undefined method 'decode_www_form' for URI:Module (NoMethodError). What could be the reason?
    – myhd
    Oct 10, 2012 at 19:24
  • @myhd Looks like the method was added in Ruby 1.9.2
    – steenslag
    Oct 10, 2012 at 20:05
  • @steenslag Too bad! I’m (still) on 1.8.7 (OSX), but I really appreciate your answer.
    – myhd
    Oct 10, 2012 at 20:33
  • 1
    there needs to be an "if(uri.query != nil)" after uri = URI.parse(str). Otherwise, uri.query is nil. Oct 14, 2015 at 16:04
  • I like the answer above (the checkmarked one) because this one can screw up foreign characters in the URL. The regex looks like a hack but actually works and preserves the stuff in the URL Feb 1, 2017 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.