Nortain
Nortain

Reputation: 143

Is it possible to select or highlight a substring of text within a text box using watir?

I'm relatively new to ruby and watir but am trying to build a ruby script that will select a given subset of a string out of a text box.

Example given the string:

"Here Here!" 

I would like to be able to select the second instance of "Here"

I've been using watir-webdriver/extensions/select_text.rb thinking that I could use this to accomplish my goal but as far as I can tell it can only selected the first matching text of an element. I was hoping for something that could take in a beginning and ending index and select only those characters. Does anyone know if something like that exists in ruby?

Upvotes: 2

Views: 488

Answers (1)

paul
paul

Reputation: 4487

Save the text in a variable.

Lets say your variable is test_string = "Here Here!"

Now split it using .split method like this

words = test_string.split(" ")

words is an array whose contents are Here at index 0 and Here! at index 1 (Array in any language starts from zero).

Now you can call any instance you wish. If you want second, get it like this:

puts words [1] this will give you Here!

test_string = "Here Here!"
words = test_string.split(" ")
puts words [1]

OR

test_string = @browser.___your_locator__.text
words = test_string.split(" ")
puts words [1]

Upvotes: 1

Related Questions