A website has multiple pages with imported HTML from another page with id tags that need to be simplified.
It currently looks like this.
<h2> <a id="user-content-test1" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="user-content-best2" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="user-content-nest3" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="user-content-rest4" href="https://www.example.com"> Anything </a> </h2>
There are anchor links that point to all of these ids, but these links do not include the “user-content-” part. They look like this Link to anchor. They do NOT look like this Link to anchor. There are too many of these id’s to change manually.
How can I change the value of all the id tags from id="user-content-test1
to just id="test1
using jQuery or pure JS? The desired result should be:
<h2> <a id="test1" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="best2" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="nest3" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="rest4" href="https://www.example.com"> Anything </a> </h2>
I have searched all over stackoverflow and google but I only find how to replace strings, not IDs. I have tried both of these scripts with no results.
<script> $(document).ready(function(){ let result = 'user-content-'.replaceAll(/+/g, ' '); }); </script>
<script> $(document).ready(function(){ var find = 'user-content-'; var re = new RegExp(find, 'g'); str = str.replace(re, '');}); </script>
Advertisement
Answer
use the selector $("h2 a[id^=user-content]")
-> that means select all id beginning by user-content
$(document).ready(function() { $("h2 a[id^=user-content]").each((i, e) => { let id = $(e).attr("id"); $(e).attr("id", id.replace("user-content-", "")); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2> <a id="user-content-test1" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="user-content-best2" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="user-content-nest3" href="https://www.example.com"> Anything </a> </h2> <h2> <a id="user-content-rest4" href="https://www.example.com"> Anything </a> </h2>