Reputation: 60213
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 /?|.=%:
Upvotes: 0
Views: 1614
Reputation: 434665
The gsub
method can take a string or a Regexp as its first argument, same goes for gsub!
. For example:
>> 'here is some ..text.. xxtextxx'.gsub('..text..', 'pancakes')
=> "here is some pancakes xxtextxx"
So you don't need to bother with a regex or escaping at all, just do a straight string replacement:
html.gsub!(url, new_url)
Or better, use an HTML parser to find the particular node you're looking for and do a simple attribute assignment.
Upvotes: 2
Reputation: 54984
I think you're looking for something like:
path_regexp = Regexp.new(Regexp.escape(url))
Upvotes: 2