user2931706 user2931706 - 6 months ago 9
Ruby Question

How to replace HTML input value in Ruby?

I have a string of html:

string = "<input type=text name='email' value='mike@mail.com'> <input type=hidden name='pin' value='123'>"


And I want replace the value of
email
to stars
*******


"<input type=text name='email' value='*******'> <input type=hidden name='pin' value='123'>"


so I have something like this:

string.gsub(/<input(.*?)name='email'(.*)value='(.*?)'/, '*******')


https://regex101.com/r/dO1uJ3/2

I do know that my regex is invalid, so asking for help.

p.s I don't want to use Nokogiri, just plain regex with string

Answer

create capture groups (()) before and after of what you want to replace, then use them for replacement \1****\2, i.e.:

result = subject.gsub(/('email'\s+value=').*?('>)/i, '\1*****\2')

https://regex101.com/r/dO1uJ3/1


Comments