Let’s say I have an array with url’s (displayed with href
attributes) (don’t ask me why, it’s just like that):
var MyArray = [
'<a href="http://www.facebook.com/"></a>',
'<a href="http://www.twitter.com/"></a>',
'<a href="http://www.cnn.com/"></a>'
];
I want to make a new Array, with the same url’s but without the anchor tag <a href=""></a>
, so something like this:
var MyNewArray = [
"http://www.facebook.com/”,
"http://www.twitter.com/",
"http://www.cnn.com/"
];
Some HTML magic is necessary here… Thank you guys!
One option is to append the elements to a temporary DOM container element and then use the native DOM API methods/properties in order to retrieve the desired attribute(s).
In the example below, you can pass the array of elements to a function which will create a temporary div
container element. The container's innerHTML
property is then set to the joined list of anchor elements. From there you can access the native href
property and return a mapped array of all the values.
The benefit to this approach is that it will work even if the anchor element string has multiple different attributes in varying order. It would also work if single quotes are used around the href
value rather than double quotes.
function getAnchorHrefAttributes(elementsArray) {
var container = document.createElement('div');
container.innerHTML = elementsArray.join(' ');
return Array.from(container.querySelectorAll('a')).map((a) => a.href);
}
var anchors = ['<a href="http://www.facebook.com/" class="test">1</a>',
'<a href="http://www.twitter.com/"></a>',
'<a href="http://www.cnn.com/"></a>'
];
function getAnchorHrefAttributes(elementsArray) {
var container = document.createElement('div');
container.innerHTML = elementsArray.join(' ');
return Array.from(container.querySelectorAll('a')).map((a) => a.href);
}
var hrefs = getAnchorHrefAttributes(anchors, 'href');
console.log(hrefs);
Alternatively, you could also use a basic regular expression such as /href="([^"]+)"/
in order to capture the href
attribute value. However, I would highly suggest avoiding regular expressions for this in favor of the solution above for the aforementioned reasons.
function getAnchorHrefAttributes(elementsArray) {
return elementsArray.map((a) => {
var match = a.match(/href="([^"]+)"/);
return match ? match[1]: null;
});
}
var anchors = ['<a href="http://www.facebook.com/" class="test">1</a>',
'<a href="http://www.twitter.com/"></a>',
'<a href="http://www.cnn.com/"></a>'
];
function getAnchorHrefAttributes(elementsArray) {
return elementsArray.map((a) => {
var match = a.match(/href="([^"]+)"/);
return match ? match[1] : null;
});
}
var hrefs = getAnchorHrefAttributes(anchors, 'href');
console.log(hrefs);