我从之前的problem获得了这个功能,但它很有效但我刚刚意识到我的链接集合需要删除基本URL。
这些是我认为会删除baseURL的部分:
<div class="row">
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
<div class="col-sm-4">
<div class="list-image border-one">
<?php the_post_thumbnail( ''); ?>
</div>
<div class="list-info">
<h2>Please Help Refugees</h2>
<p><span>85%</span> Donated / <span>$7,291</span> To Go</p>
<p>On the other hand, we denounce with righteous indignation and dislike.</p>
<a href="#" class="btn btn-primary">Donate Now</a>
</div>
</div>
<?php endwhile; endif; ?>
</div>
更新
我应该提到:
该功能已经可以发现链接并应用属性,但不会删除基本URL。
此:
baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/; // create the regexp
link.href.replace(baseUrlPattern ,""); // then use replace to strip it out of the URL
之后应该在DOM中看起来像这样:
<a href="http://url.nyc.com/xxx/xxx/xxx">link1</a>
JS:
<a href="/xxx/xxx/xxx" target="_blank">link1</a>
HTML:
var URLChecker = (function iffe() {
var publicAPI = {
getURL: function() {
for (var i = 0; i < arguments.length; i++) {
return {
'smo': 'http://url.nyc.com',
'smodev': 'http://smodev.rye.foo.com',
'url1_sans_3w': 'http://url1.com',
'url2': 'http://www.url2.com',
'url3': 'http://www2.url3.com'
}[arguments[i]];
}
},
searchURL: function() {
var link, url, baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/;
for (var i = 0, len = arguments.length; i < len; i++) {
url = this.getURL(arguments[i]);
for (var j = 0, jlen = document.links.length; j < jlen; j++) {
link = document.links[j];
if (link.href.indexOf(url) !== -1) {
link.setAttribute("target", "_blank");
link.href.replace(baseUrlPattern ,"");
}
}
}
}
};
return publicAPI;
})();
答案 0 :(得分:1)
你可以用不同的方式解决这个问题,其中之一是:
见下面的评论
searchURL: function() {
var link, url, parser; //added parser
for (var i = 0, len = arguments.length; i < len; i++) {
url = this.getURL(arguments[i]);
for (var j = 0, jlen = document.links.length; j < jlen; j++) {
link = document.links[j];
if (link.href.indexOf(url) !== -1) {
// create a dummy link just to get the pathname of the actual link
parser = document.createElement('a');
parser.href = link.href;
link.setAttribute("target", "_blank");
link.href = parser.pathname;
}
}
}
}
如果您还需要其他任何内容,请记住parser
只是一个锚点,以便您拥有以下内容
var href = "http://url.nyc.com/xxx/xxx/xxx";
parser = document.createElement('a');
parser.href = href;
console.dir(parser);
parser.protocol; // => "http:"
parser.hostname; // => "url.nyc.com"
parser.port; // => ""
parser.pathname; // => "/xxx/xxx/xxx"
parser.search; // => ""
parser.hash; // => ""
parser.host; // => "url.nyc.com"
答案 1 :(得分:0)
也许它已经晚了,但如果你想要
此:
<a href="http://url.nyc.com/xxx/xxx/xxx">link1</a>
之后应该在DOM中看起来像这样:
<a href="/xxx/xxx/xxx" target="_blank">link1</a>
你可以这样做
var x = 'http://url.nyc.com/xxx/xxx/xxx';
var y = x.split('/').slice(3).join('/');
console.log(y);
答案 2 :(得分:0)
使用原生方法:
var str = 'http://url.nyc.com/x/xx/xxx';
var url = new URL(url); // url.pathname == '/x/xx/xxx/'
注意:这可能不适用于Chrome;但未指定浏览器