简体   繁体   中英

Change word inside link using javascript

I have the following link:

<a class="some_class" 
href="https://example.com/text/sometext2/">

I need to change the word "text" to "sometext1" using JavaScript

Thanks!

Use document.querySelectorAll() to get a reference to your links, then iterate over the links using forEach() and use elem.getAttribute('href') and elem.setAttribute('href', value) to get and set the href attribute on each link.

To change the value, use String.replace() with a regex:

 document.querySelectorAll('a.some_class').forEach(link => { const href = link.getAttribute('href').replace(/\\/text\\//, '/sometext1/'); link.setAttribute('href', href); console.log(href); }); 
 <a class="some_class" href="https://example.com/text/sometext2/">A link</a> <a class="some_class" href="https://example.com/text/sometext2/">A link</a> <a class="some_class" href="https://example.com/text/sometext2/">A link</a> <a class="some_class" href="https://example.com/text/sometext2/">A link</a> 

Or more simply:

document.querySelectorAll('a.some_class').forEach(link => {
    link.href = link.href.replace(/\/text\//, '/sometext1/');
});

You can do this in JavaScript I believe by doing document.getElementById("your-button").href="your-page.html"; .

If you want to change all the links having some_class class, you could do this :

document.querySelectorAll("a.some_class").forEach(a => a.href.replace(/\btext\b/g, "sometext1"));

The /\\btext\\b/g regex will match every 'text' word in your string :

  • \\b asserts a word boundary , so if text is included in a word it will not match

  • The g switch makes the regex global , so it does not stop on first match

You would access the href attribute of that element. Then transform the text however you need to do so. In this case we are identifying the text by other delimiters.

var element = document.querySelector('a.some_class');
var href = element.getAttribute('href')
href = href.replace(/\/text\//, '/sometext1/');
element.setAttribute('href', href');

You can first get the element and use setAttribute method of the element where you can replace your old value

 var a = document.getElementsByTagName("a")[0]; a.setAttribute("href",a.getAttribute('href').replace("text","SomeText1")); 
 <a class="some_class" href="https://example.com/text/sometext2/"> test </a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM