最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论
(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;.

发布评论

评论列表(0)

  1. 暂无评论