How can multiple trailing slashes can be removed from a URL in Ruby

可紊 提交于 2019-12-05 04:17:18
Aliaksei Kliuchnikau

If you just need to remove all slashes from the end of the url string then you can try the following regex:

"http://emy.dod.com/kaskaa/dkaiad/amaa//////////".sub(/(\/)+$/,'')
"http://www.example.com/".sub(/(\/)+$/,'')

/(\/)+$/ - this regex finds one or more slashes at the end of the string. Then we replace this match with empty string.

Hope this helps.

Although this thread is a bit old and the top answer is quite good, but I suggest another way to do this:

/^(.*?)\/$/

You could see it in action here: https://regex101.com/r/vC6yX1/2

The magic here is *?, which does a lazy match. So the entire expression could be translated as:

Match as few characters as it can and capture it, while match as many slashes as it can at the end.

Which means, in a more plain English, removes all trailing slashes.

def without_trailing_slash path
  path[ %r(.*[^/]) ]
end

path = "http://emy.dod.com/kaskaa/dkaiad/amaa//////////"

puts without_trailing_slash path # "http://emy.dod.com/kaskaa/dkaiad/amaa"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!