2017-07-17 49 views
2

我想通过将用户发送到我的API然后重定向来跟踪链接的点击率。因此,当他们生成一个网址时,我想运行某种代码,将anchor的整个href替换为某个API呼叫加上它们的目的地。Rails/Gsub - 以编程方式锚定href的条件前缀

定期anchor例子:

<a href="http://localhost:3000/dulce.html#"></a>

由于该网址在dulce.html#结束,那么我想替换它只是#。 (<a href="#"></a>)但是,如果它不dulce.html#结束,然后我要追加东西起步阶段,所以它是这样的:

<a href="http://api.tracking.com/destination=http://localhost:3000/world.html"></a>

我有GSUB的经验非常少,似乎无法找出使这种条件转换发生的语法。

任何想法?

回答

0

您可能不需要为此使用gsub。你可以这样做:

link = '<a href="http://localhost:3000/dulce.html#"></a>' 
# Get the href 
href = /\<a\shref\=\"(.+)\"\>\<\/a\>/.match(link)[1] 

# If you want to know if the href ends with a '#' 
if href.last(1) == '#' 
    # Do something here 
    new_link = '<a href="#"></a>' 
end 

# If you want to know if it ends in 'dulce.html#' 
if href.last(11) == 'dulce.html#' 
    # Do something here 
    new_link = "<a href='http://api.tracking.com/destination=#{href}'></a>" 
    # Which would result in 
    # <a href="http://api.tracking.com/destination=http://localhost:3000/world.html"></a> 
    # If href is http://localhost:3000/world.html 
end 

您可以使用优秀的http://www.regexpal.com/来测试你的正则表达式。

希望这会有所帮助!