user2187420
user2187420

Reputation: 39

Regex simply not working in IE 8, 9 and 10

Here is our text to replace:

<A href="http://domain.com"><IMG src="https://domain.com/images/siteheader.jpg"></A>

Using javascript .replace, we try to replace with blank space using the following:

.replace ("/<A href=\"http:\/\/domain.com\"><IMG src=\"https:\/\/domain.com\/images\/siteheader.jpg\"><\/A>/i"," ");

In all other browsers this seems to work, but not in IE. I even tried using this online regex validator: http://www.online-toolz.com/tools/regexp-editor.php and it says it's valid. Kind of stumped. Is IE doing something out of the norm?

Upvotes: 0

Views: 720

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Regexes are literals and should not have quotes around them:

.replace(/your regex here/,'replacement')

That being said, where is the text coming from? If it's coming from .innerHTML, browsers may return a string that is different from what you literally have in the source (for instance, attribute names may be uppercased, or the attributes themselves swapped. I believe older versions of IE strip out quotes around single-word attribute values, which would also mess with your regex.

In short, you should not use a regex for this. You could try this instead:

var toRemove = document.querySelector("a[href='http://domain.com']"),
    parent = toRemove.parentNode;
parent.removeChild(toRemove);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074208

You either use a string (the literal form of which looks like "...") or a regular expression (the literal form of which looks like /.../) with replace. You're trying to do both simultaneously. Remove the quotes:

.replace (/<A href="http:\/\/domain.com"><IMG src="https:\/\/domain.com\/images\/siteheader.jpg"><\/A>/i, " ");

When you use a string, it's just matched literally, no regular expression processing is done.

I haven't validated the entire contents of the regex, just removed the surrounding " and removed the \ in front of the embedded ".

Upvotes: 6

Related Questions