Найдите ссылки, содержащие определенную строку в href, и удалите href между слешами только с помощью javascript - PullRequest
0 голосов
/ 19 февраля 2019

У меня есть сценарий использования, где я должен выбрать все <a>, содержащие строку в URL, например, "/ web / local", и удалить "/ web / local" из всех href всех этих ссылок.

Примечание: я не могу использовать jQuery.Я могу использовать чистый JS или YUI.

Заранее спасибо.

Ответы [ 3 ]

0 голосов
/ 19 февраля 2019

См. Встроенные комментарии:

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>
0 голосов
/ 19 февраля 2019

Чтобы правильно получить / установить атрибут 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 голосов
/ 19 февраля 2019
    <!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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...