views:

58

answers:

3
+2  Q: 

.replace problem

I have a problem with html().replace:

<script type="text/javascript">
  jQuery(function() { 
  jQuery(".post_meta_front").html(jQuery(".post_meta_front").html().replace(/\<p>Beschreibung:</p> /g, '<span></span>'));
});
</script>

what is wrong in my script?

A: 

It looks like you're not escaping all of the special characters in the find parameter of the replace function. You're only escaping the first < character.

Try something like:

/\<p\>Beschreibung:\<\/p\>/g

Note that replace is a function of javascript not jQuery.

Damovisa
Thansk Damovisa. You were right.
chris
+1  A: 

You need to escape forward slashes / in the regex part.

<script type="text/javascript">
  jQuery(function() { 
  jQuery(".post_meta_front").html(jQuery(".post_meta_front").html().replace(/<p>Beschreibung:<\/p> /g, '<span></span>'));
});
</script>
Ruel
+4  A: 

Why are you using regex for this?

If you want to replace an element with another, you can use jQuery's .replaceWith() method.

jQuery(".post_meta_front p:contains('Beschreibung:')")
                                               .replaceWith('<span></span>');

Or if you need to ensure an exact match on the content:

jQuery(".post_meta_front p").filter(function() {
    return $.text([ this ]) === 'Beschreibung:';
}).replaceWith('<span></span>');
patrick dw
+1. Relying on the format of the output of `html()` at all is inadvisable (different browsers will give different text escaping, element case and attribute quoting formatting). Using DOM-style methods like this is more reliable, and doesn't unnecessarily destroy and re-create all the other nodes you are not replacing.
bobince