views:

206

answers:

3

Hello everyone.

I have following JS code (stripped to minimal size where problem still exists)

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="debug">this is <em>test</em></div>
<script type="text/javascript">
    var string1 = $('#debug').html();
    var string2 = string1.replace(/<em>/g, '<strong>');
    string2 = string2.replace(/<\/em>/g, '</strong>');
    $('#debug').html( string2 );
</script>
</body>
</html>

In Firefox everything works and <em> tags are replaced with <strong>.

But in Opera <em>'s are stay in place. Furthermore, any other HTML tags are not captured by regexps at all.

Is there any way to fix this behaviour? I need not only to replace tags, but to parse their content too (href attributes for example).

+2  A: 

Opera returns tags as uppercase, e.g. <EM>. You need to change your regular expressions to work case-insensitively:

var string2 = string1.replace(/<em>/gi, '<strong>');
string2 = string2.replace(/<\/em>/gi, '</strong>');
Phil Ross
Thanks, it works.Anyway, this is very strange behaviour :)
technix.in.ua
@technix.in.ua Opera is just creating a normalized representation of the source HTML and chooses to make tag names uppercase. Firefox does the opposite and makes all tag names lowercase.
Phil Ross
scunliffe
I don't quite understand the assertation that tag and attribute names are "meant to be" lowercase. The logic for doing what IE does is very simple: IE invented innerHTML, so they are by definition correct and browsers who want to support it should figure out what IE does. (Of course it's now being standardised in HTML5, so when HTML5 is released this no longer applies.)
hallvors
A: 

Your regular expressions aren't matching in Opera as it has normalised all HTML tags to uppercase try with //gi

However if you are doing more changes ("parsing their content"), I really would recommend doing proper DOM manipulation and not using regular expressions.

Sharebear
+1  A: 

Don’t use string methods when you can use DOM methods:

$("#debug em").each(function() {
    var newElem = document.createElement("strong");
    for (int i=0; i<this.childNodes.length; ++i) {
        newElem.appendChild(this.childNodes[i]);
    }
    this.parentNode.replaceNode(newElem, this);
});
Gumbo
This is a much better approach :)
hallvors