-1

I have a rails application where I am using kaminari for pagination.

Somehow kaminari is using wrong url for hyperlinks.

Right now I am looking for an easy fix which requires some regex & gsubbing.

I have this url from kaminari:

"/bookings/hotels//Pune?arrival_date=....."

I want to replace this part - /hotels//Pune? with this - /hotels?

There could be any other string in place of Pune (it might change).

How should I do this ?

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
RamanSM
  • 275
  • 3
  • 13

3 Answers3

2

Capture and replace using match capture

gsub(/hotels(\/\/\w+)\?/){|m| m.gsub($1, '')}

str = "/bookings/hotels//Pune?arrival_date=....."
str.gsub(/hotels(\/\/\w+)\?/){|m| m.gsub($1, '')}

#=> "/bookings/hotels?arrival_date=....."
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
1

I always use the URI library when messing around with URLs, it does some of the legwork for you (especially if query strings are involved).

Something like this would suit your situation, although there's probably a way to get the right URL in the first place too!

require 'uri' # probably not necessary if you are using Rails

old_url  = "/bookings/hotels//Pune?arrival_date=blahblah"
uri      = URI(old_url)

# remove everything between the first double '//' and the end of the string
uri.path = uri.path.gsub(/\/\/.+\Z/, '')
# => "/bookings/hotels"

# output a new url using the new path but including the original query string
new_url  = uri.to_s
# =>  "/bookings/hotels?arrival_date=blahblah"
omnikron
  • 2,211
  • 17
  • 30
0

gsub("//Pune", "") No needs 4 regexp here.

plombix
  • 396
  • 3
  • 13
  • Well I have to say sorry as I didn't mention that Pune part would be dynamic. I will edit the question. – RamanSM Sep 07 '16 at 13:16