admin管理员组

文章数量:1425800

(function( $ ) {

    $.fn.htmlCodes = function(){
        var $this = this;
        var body = this.html();
        body = body.replace(':)', '&#9786;').replace('<3', '&#9829;');
        this.html(body);
    };  


})( jQuery );

I wrote this JQuery plugin so that it would change smiley faces to the smiley face entity. (and heart)

However, the heart doesn't work! For some reason the smiley works but heart doesn't.

(function( $ ) {

    $.fn.htmlCodes = function(){
        var $this = this;
        var body = this.html();
        body = body.replace(':)', '&#9786;').replace('<3', '&#9829;');
        this.html(body);
    };  


})( jQuery );

I wrote this JQuery plugin so that it would change smiley faces to the smiley face entity. (and heart)

However, the heart doesn't work! For some reason the smiley works but heart doesn't.

Share Improve this question asked Feb 21, 2012 at 3:23 TIMEXTIMEX 273k368 gold badges802 silver badges1.1k bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

Works if you do this...

.replace('&lt;3', '&#9829;');

DEMO: http://jsfiddle/ZdJh5/

The .html() is giving you the HTML character code for the < symbol.

A < is a special character in HTML, which is what jQuery's html function will return, and so you need to replace &lt; instead of <. Also, for a catch-all, you should use the /g flag:

(function( $ ) {

    $.fn.htmlCodes = function() {
        var $this = this;
        var body = this.html();
        body = body.replace(/:\)/g, '&#9786;').replace(/&lt;3/g, '&#9829;');
        this.html(body);
    };  

})( jQuery );

Otherwise, only the first instance will be replaced. And a quick demo to show that it works. ☺

body = body.replace(':)', '&#9786;').replace('&lt;3', '&#9829;');

It is possible < gets encoded as &lt;.

本文标签: jqueryHow come this javascript does not replace text with the quotheartquot symbolStack Overflow