views:

677

answers:

3

I have a string that may have a path to a file. Example src="/folder/whatever". How do I replace that path with src="http://www.sitename.com/folder/whatever ?

+1  A: 

If your string contains src="/...", possibly many times, do this:

string.gsub!(/\bsrc="(\/[^"]*)"/, 'src="http://www.sitename.com\1"')

If your string contains the URL only, do this:

src.replace('http://www.sitename.com' + src)

More information about String#gsub and String#gsub! here: http://www.ruby-doc.org/core/classes/String.html#M000832

pts
That would work if I just wanted to append the full url to the front of the string, but I need to find the src inside of a string and then change that src
Added another answer which finds all instances of src=
pts
A: 

route helpers. use url instead of path.

kajaco
A: 

i like pts's solution, but i might remove the slash from the regex...so it would be:

string.gsub!(/\bsrc="([^"]*)"/, 'src="replacement_text\1"')

use the \1 to access the back reference

Tony