How to replace only part of the value of an attribute?

0

I want to replace ONLY PART of the value of href attributes in a document but I can not find it well how to do it, to see if someone gives me a help. I add that I want to do it only with Javascript, without Jquery or another library.

I want to find all the elements whose value of their href attribute starts with "/pagina/" , this is easy:

var x = document.querySelectorAll('[href^="/pagina/"]');

It returns a list of nodes, what I do not find how to do is to replace ONLY ONE PART of the value of that attribute, I want to replace: href="/pagina/01345" by href="/pagina_local/01345"

That is to say only "pagina" by "

pagina_local.x[0].getAttributeNode("href").value;

//Devuelve:  '/pagina/01345'

I have to get it back: /pagina_local/01345

Maybe I have to do it in several steps but it may be that there is an easier solution so I ask here, thank you very much.

    
asked by Daniel Martinez 09.09.2018 в 08:13
source

1 answer

2

The method String.prototype.replace () should do what you want:

[].forEach.call(document.querySelectorAll('[href^="/pagina/"]'), function(elem) {
    elem.setAttribute('href', elem.getAttribute('href').replace('pagina', 'pagina_local'));
});
    
answered by 09.09.2018 в 08:53