Javascript用正则表达式"修复"所有类的hrefs

Dan*_*Dan 1 javascript

假设我在页面上有一堆链接,例如:

<a class="eg-vimeo1-element-0 eg-post-14" href="http://255972693" target="_self"><i class="eg-icon-play"></i></a>
Run Code Online (Sandbox Code Playgroud)

我想每一个改变http://255972693https://vimeo.com/video/255972693

我试着看看我的hrefs:

let e = document.getElementsByClassName("eg-vimeo1-element-0");
for (var i = 0; i < e.length; i++){
  console.log(e[i].href);
  console.log(e[i].href.replace("http://", "https://vimeo.com/video"));
}
Run Code Online (Sandbox Code Playgroud)
<a class="eg-vimeo1-element-0 eg-post-14" href="http://255972693" target="_self"><i class="eg-icon-play"></i></a>
Run Code Online (Sandbox Code Playgroud)

但它将href转换为IP并给出结果

http://vimeo.com/video/15.65.213.85/
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 6

如果您getAttribute在href属性上使用它将起作用.

const e = document.getElementsByClassName("eg-vimeo1-element-0")

for (var i = 0; i < e.length; i++) {
  const href = e[i].getAttribute('href');
  e[i].href = href.replace("http://", "https://vimeo.com/video/");
}
Run Code Online (Sandbox Code Playgroud)
<a class="eg-vimeo1-element-0 eg-post-14" href="http://255972693">link</a>
Run Code Online (Sandbox Code Playgroud)

这是更新后的jsFiddle.

并保留Niet the Dark Absol的评论,以防它消失:

"这是有效的,而.href不是因为.href是已解析的URL,并被http://1234567解释为十进制形式的IP地址."

  • 这有效的原因和`.href`不是因为`.href`是*已解析的*URL,而`http:// 1234567`被解释为十进制形式的IP地址. (4认同)