Fnd链接包含href中的特定字符串,并仅使用javascript删除斜杠之间的href

问题描述 投票:1回答:3

我有一个用例,我必须选择所有<a>,包含url中的字符串,如“/ web / local”,并从所有这些链接的所有href中删除“/ web / local”。

注意:我不能使用jQuery。我可以使用纯js或YUI。

提前致谢。

javascript yui
3个回答
1
投票

请参阅内联评论:

let phrase = "/web/local";

// Get all the links that contain the desired phrase into an Array
let links = Array.prototype.slice.call(document.querySelectorAll("a[href*='" + phrase +"']"));

// Loop over results
links.forEach(function(link){
  // Remove the phrase from the href
  link.href = link.href.replace(phrase, "");
});

// Just for testing:
console.log(document.querySelectorAll("a"));
<a href="http://www.something.com/web/local">Some Link</a>
<a href="http://www.something.com/web/local">Some Link</a>
<a href="http://www.something.com/web/local">Some Link</a>
<a href="http://www.something.com/web/local">Some Link</a>
<a href="http://www.something.com/web/local">Some Link</a>

1
投票

为了正确获取/设置href属性,您需要使用getAttribute / setAttribute

document.querySelectorAll('a[href*="/web/local"').forEach(function(ele) {
  ele.setAttribute('href', 
           ele.getAttribute('href').replace('/web/local', ''));

    console.log(ele.outerHTML);
});
<a href="/web/local"></a>
<a href="22222/web/local"></a>
<a href="/web/local"></a>

0
投票
    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <a href="http:///web/locale/google.com">Link 1</a>
    <a href="http:///web/locale/stackoverflow.com">Link 2</a>


    <script>

        var string = '/web/locale/';
        var links = document.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
            var link = links[i].getAttribute('href');
            link = link.replace(string, '');
            links[i].setAttribute('href', link);

        }
    </script>


</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.