ruby - How to replace string in URL with captured regex pattern -
i want replace 'hoge' 'foo' regex. user's value dynamic can't use str.gsub('hoge', 'foo').
str = '?user=hoge&tab=fuga' what should do?
don't regular expression.
this how manipulate uris using existing wheels:
require 'uri' str = 'http://example.com?user=hoge&tab=fuga' uri = uri.parse(str) query = uri.decode_www_form(uri.query).to_h # => {"user"=>"hoge", "tab"=>"fuga"} query['user'] = 'foo' uri.query = uri.encode_www_form(query) uri.to_s # => "http://example.com?user=foo&tab=fuga" alternately:
require 'addressable' uri = addressable::uri.parse('http://example.com?tab=fuga&user=hoge') query = uri.query_values # => {"tab"=>"fuga", "user"=>"hoge"} query['user'] = 'foo' uri.query_values = query uri.to_s # => "http://example.com?tab=fuga&user=foo" note in examples order of parameters changed, code handled difference without problems.
the reason want use uri or addressable because parameters , values have correctly encoded when contain illegal characters. uri , addressable know rules , follow them, whereas naive code assumes it's ok not bother encoding, causing broken uris.
uri part of ruby standard library, , addressable more full-featured. take pick.
Comments
Post a Comment