如何删除JS文本/模板中的默认链接

use*_*837 2 javascript php jquery backbone.js

任何人都可以帮助我如何删除或替换JS模板中的现有链接.我使用backbone.js.

这是我的代码:

<script id="option-show-template" type="text/template">
<address>
   <abbr title="Website">Web :</abbr> <%= (website)? '<a href="'+ website +'" id="website">' + website + '</a>' : ''  %></address>
</script>
Run Code Online (Sandbox Code Playgroud)

输出:

Web: www.test.com
Run Code Online (Sandbox Code Playgroud)

问题是即使它会输出正确的数据,但href attr并不完全显示正确的数据.我的localhost/testserver包含在href属性中.

Web: <a href="localhost/testserver/www.test.com">www.test.com</a>
Run Code Online (Sandbox Code Playgroud)

我想要的是删除默认的基本网址.必须像这样输出:

Web: <a href="www.test.com">www.test.com</a>
Run Code Online (Sandbox Code Playgroud)

Nit*_*mar 8

http://

试试这个

 <abbr title="Website">Web :</abbr> <%= (website)? '<a href="http://'+ website +'" id="website">' + website + '</a>' : ''  %></address>
Run Code Online (Sandbox Code Playgroud)


xii*_*dea 7

这有什么不对?

实现的问题是,当您设置href没有任何协议的属性(http,https,ftp等)时,浏览器会将链接视为相对路径.因此,当您在页面上查看页面时http://localhost/testserver/,您的页面就成了localhost/testserver/www.test.com

怎么修??

简而言之,要解决问题,您需要http://在网址前添加,如果没有.您可以通过多种方式实现这一目标,例如:

  1. 按照Nitish Kumar的建议更新您的模板.
  2. http://使用jquery 替换所有url prepend
  3. ....或许多其他方式!

选项1或2很容易实现并且可以解决您的问题,如果您确定您URLs将始终像您的示例.但是对于以下用例会失败:

  1. 如果你的网址已经有了协议(即http://google.com).然后你的网址就会变成http://http://google.com
  2. 如果你的网址真的是一个相对网址(即my/relative/url).然后它应该保持不变,但你会得到无域名的无效网址 - http://my/relative/url

终极解决方案!!

因此,您可以使用以下功能来修复您的URL

//Check if it is a valid URL with FQDN
function isValidUrl(url) {
    return url.match(/((ftp|http|https):\/\/)?[\w\-]+\.[\w\-]+/);
}

//Check if the url already contain a protocol or not
function hasProtocol(url){
    return url.match(/(ftp|http|https):\/\//);
}

//Fix your URL only if needed!!
function setHttp(link) {
    return (!isValidUrl(link) || hasProtocol(link)) ? link : 'http://' + link;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过多种方式使用此功能来解决问题.您可以在此处找到示例实现

快乐的编码!!