0

Trying to a add target="_blank" to all tags using javascript in a string.

Why does this work:

var editdescription = itemdescription.replace(new RegExp("All","g"),"Every");

But not this?

var editdescription = itemdescription.replace(new RegExp("<a","g"),"<a target="_blank"");
danssker
  • 575
  • 3
  • 7
  • 18

2 Answers2

5

You've nested your double quotes incorrectly. Instead of

"<a target="_blank""

try escaping the double quotes:

"<a target=\"_blank\""

The way you wrote it was treated as two separate strings, "<a target=" and "" with _blank in between.

And as stated so many times before, preferably don't parse HTML with regex.

Community
  • 1
  • 1
Maehler
  • 6,111
  • 1
  • 41
  • 46
  • fantastic - thank you! Excuse my ignorance but why do the forward slashes work? – danssker May 17 '12 at 15:45
  • 1
    @danssker With the *backslashes* you escape the quotes and thus tell javascript that they should be treated as characters and not as the beginning/end of a string. – Maehler May 17 '12 at 15:54
1

You should not try to process HTML with regex, as there are too many things that could go wrong. In this case, what if you have the tag as <A HREF...>? Or what about other tags that start with a such as <area>, <abbr>, <acronym> and so on? What if there's already a target attribute?

Instead, try treating the HTML as HTML and not as plain text. You have an engire engine at your fingertips.

var tmp = document.createElement('div');
tmp.innerHTML = itemdescription;
var links = tmp.getElementsByTagName('a'), l = links.length, i;
for( i=0; i<l; i++) {
    links[i].setAttribute("target","_blank");
}
editdescription = tmp.innerHTML;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • This is what I used successful before, but I had no success getting it to work from within another loop. And I 'm fairly sure that there no other targets because the string comes out of Google feed Api which seems to strip them all out for some reason. – danssker May 17 '12 at 18:16