Get string between two strings

/ Published in: Ruby
Save to your folder(s)

If you're using Rails and want to make this a global function, drop this into your application_controller and call it as a function.

# get_string_between("hellomyfriendmoto", 'o', 'm')
# > myfriend

Copy this code and paste it in your HTML
  1. def get_string_between(my_string, start_at, end_at)
  2. my_string = " #{my_string}"
  3. ini = my_string.index(start_at)
  4. return my_string if ini == 0
  5. ini += start_at.length
  6. length = my_string.index(end_at, ini).to_i - ini
  7. my_string[ini,length]
  8. end

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.