In Ruby, I want to replace a given URL in an HTML string.
Here is my unsuccessful attempt:
escaped_url = url.gsub(/\//,"\/").gsub(/\./,"\.").gsub(/\?/,"\?")
path_regexp = Regexp.new(escaped_url)
html.gsub!(path_regexp, new_url)
Note: url is actually a Google Chart request URL I wrote, which will not have more special characters than /?|.=%:
The
gsubmethod can take a string or a Regexp as its first argument, same goes forgsub!. For example:So you don’t need to bother with a regex or escaping at all, just do a straight string replacement:
Or better, use an HTML parser to find the particular node you’re looking for and do a simple attribute assignment.