danssker
danssker

Reputation: 585

Trying to edit all <a> in a string

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"");

Upvotes: 0

Views: 94

Answers (2)

Maehler
Maehler

Reputation: 6331

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.

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

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;

Upvotes: 1

Related Questions