删除“www"、“http://"从字符串 [英] Remove "www", "http://" from string
本文介绍了删除“www"、“http://"从字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 Ruby 从字符串中删除www"、http://"、https://"?
How can I remove "www", "http://", "https://" from strings using Ruby?
我试过了,但没有用:
s.gsub('/(?:http?:\/\/)?(?:www\.)?(.*)\/?$/i', '')
这是我在 Rails 中所做的:
Here what I'm doing in Rails:
<%= auto_link(job.description) do |url| url.truncate(25).gsub('http://', '') end %>
网址被截断,但我的目标是删除链接的开头,例如www"或http://",因此链接看起来像google.com/somepage/d...",不像http://google.com/some..."
Url are truncated, but my goal is to remove the beginning of the links, such as "www" or "http://" so the link would look like "google.com/somepage/d...", not like "http://google.com/some..."
推荐答案
s = s.sub(/^https?\:\/\//, '').sub(/^www./,'')
如果你不想使用 s =
,你应该使用 sub!
s 而不是所有的 sub
s.
If you don't want to use s =
, you should use sub!
s instead of all sub
s.
您的代码存在的问题是:
The problems with your code are:
- 问号总是跟在一个可选字符之后
- 始终替换子程序中的一种模式.您可以链接"多个操作.
- 在 Regexp 的开头使用
sub
而不是gsub
和^
所以它只替换http://代码> 在开头,但将代码留在中间.
- Question mark always follows AFTER an optional character
- Always replace one pattern in a sub. You can "chain up" multiple operations.
- Use
sub
instead ofgsub
and^
in the beginning of Regexp so it only replaces thehttp://
in the beginning but leaves the ones in the middle.
这篇关于删除“www"、“http://"从字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文