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?
user113716
323k64 gold badges454 silver badges441 bronze badges
-
It would be good if you described what the problem is. And posted your HTML or at least a short extract.Strelok– Strelok2010年09月30日 00:15:52 +00:00Commented Sep 30, 2010 at 0:15
-
need quotes around the regex maybe?Ascherer– Ascherer2010年09月30日 00:16:15 +00:00Commented Sep 30, 2010 at 0:16
3 Answers 3
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>');
answered Sep 30, 2010 at 0:21
user113716
323k64 gold badges454 silver badges441 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
bobince
+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.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>
answered Sep 30, 2010 at 0:18
Ruel
15.9k7 gold badges41 silver badges49 bronze badges
Comments
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.
answered Sep 30, 2010 at 0:16
Damovisa
19.4k16 gold badges69 silver badges89 bronze badges
Comments
lang-js