Let's say you have your string "<a href='project.php?id=5'>test</a>"
Using regular expressions to parse HTML can get real ugly real fast (what if the a has more attributes? What if there are multiple tags there?)
The cleanest would be to dump it in a new HTML element and process it as HTML using the powerful native built in DOM API instead of as a string.
var temp = document.createElement("div");
temp.innerHTML = "<a href='project.php?id=5'>test</a>";
var url = temp.firstChild.href; // now contains project.php?id=5
Now we can use more traditional tools to extract the id
var id = url.split("=")[1]; // the first thing after =.
More generally the strategy is:
- Create an empty element or a fragment and put our HTML there
- Use DOM querying methods to find our elements, in this case
.firstChild was enough but getElementsByTagName or even querySelector might be useful.
- Once we got the attribute, it's just a simple string, and we can safely use regex for it, or any other string processing method we choose.
If you're unacquainted with the DOM API this tutorial is a good place to start. It's how we process the document with JavaScript and knowing it is important to your success as a front end JavaScript developer.
data-attributes? It would make your life a bit easier, and your javascript code much cleaner.data-attributes like this is a horrible broken approach that disregards separation of concerns and how applications should be structured. The ID of the project has nothing to do with the presentation, storing your data on the DOM instead of in JavaScript is a blatent disregard of how an application should be structured. You need to aspire to a single source of truth in your application. Storing data in the DOM instead of in JS objects (like any sensible design in any UI ever does) is a recipe for code spaghetti.href- as well as thedata-attribute). However, your point of storing data in the DOM instead of in JS objects is still unclear to me.