jquery - How come this javascript does not replace text with the "heart" symbol? - Stack Overflow

(function( $ ) {$.fn.htmlCodes = function(){var $this = this;var body = this.html();body = body.replace

(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;.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745413778a4626653.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信