3

I think I have a string like:

<a href="site/project/109#" target="_blank">href</a> text, text, <a href="/target" class="test">test</a>

And I need to output

 site/project/109# text, text, test

I can find all links

var txt = msg.match(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi);

And in loop make replace. But I would like to shorten the code, do everything through single replace, like this :

var txt = msg.replace(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi, $1); 

But in this case I get: [object HTMLHeadElement]

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

2 Answers2

3

Never use regex to parse HTML, it's better to generate an element with the content and do the rest on the element.

var str = '<a href="site/project/109#" target="_blank">href</a> text, text, <a href="/target" class="test">test</a>';

// create an element
var temp = document.createElement('div');

// set the content with the string
temp.innerHTML = str;

// get all `a` tags and convert into array
// for older browser use `[].slice.call() 
// for converting into array
Array.from(temp.querySelectorAll('a')).forEach(function(ele) {
  // create a text node with the attribute value 
  var text = document.createTextNode(ele.getAttribute('href'));
  // replace a tag wit the text node
  ele.replaceWith(text);
});

// get the updated html content
console.log(temp.innerHTML)

Why not regex ? : RegEx match open tags except XHTML self-contained tags


UPDATE : The msg variable is an element object, a not string that's why it's getting converted to [object HTMLHeadElement](HTMLHeadElement refers to the HEAD tag, I think something wrong with your core check that also). So do the same as above where replace temp with the msg. In case you want to keep the original element content then generate temp element as above and set content as temp.innerHTML = msg.innerHTML .

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

If you're using jQuery (which is great and does all things) then you can get the href quite easily:

var string = '<a href="site/project/109#" target="_blank">href</a> text, text, <a href="/target" class="test">test</a>';
var href = $(string).attr('href');

which means that setting the text of the anchor tag is trivial:

$(string).text($(string).href));
theonlygusti
  • 11,032
  • 11
  • 64
  • 119