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

javascript - Jquery Function required to replace content in a String - Stack Overflow

programmeradmin0浏览0评论

I have a textarea where users can type content and also include emoticon symbols like :) or ;)

When 'Sent' is pressed the textarea string needs to be parsed to convert any emoticon symbols into <img>'s for display.

I can easily generate a list of emoticons and there relevant image like:

 ':)' - '<img src="/images/happy.jpg"/>'
 ';)' - '<img src="/images/wink.jpg"/>'

I assume the above could be put into an associate array.

Can someone point me in the right direction to create an associate array of emoticon symbol's and html img tags and then parse a string to replace the matching symbols with the html img tags?

Also out of interest is there a better way to do this?

thankyou

I have a textarea where users can type content and also include emoticon symbols like :) or ;)

When 'Sent' is pressed the textarea string needs to be parsed to convert any emoticon symbols into <img>'s for display.

I can easily generate a list of emoticons and there relevant image like:

 ':)' - '<img src="/images/happy.jpg"/>'
 ';)' - '<img src="/images/wink.jpg"/>'

I assume the above could be put into an associate array.

Can someone point me in the right direction to create an associate array of emoticon symbol's and html img tags and then parse a string to replace the matching symbols with the html img tags?

Also out of interest is there a better way to do this?

thankyou

Share Improve this question edited Nov 17, 2012 at 2:38 Samuel Rossille 19.9k18 gold badges65 silver badges92 bronze badges asked Nov 17, 2012 at 2:34 AdamAdam 21k38 gold badges131 silver badges220 bronze badges 2
  • 3 Why would you convert emotion strings to <img src ... and save it that way on your server side? I would save them as they are in the database. However, when rendering the view (webiste for example) I would have a function to convert each smiley to certain IMG... – salih0vicX Commented Nov 17, 2012 at 2:40
  • Sounds like a job for JavaScript. – Samuel Edwin Ward Commented Nov 17, 2012 at 2:40
Add a ment  | 

4 Answers 4

Reset to default 5

You actually quite described the behavior:

var map = {
    ':)':   '<img src="/images/happy.jpg"/>',
    ';(':   '<img src="/images/wink.jpg"/>'
},
text    = document.getElementsByTagName('textarea')[ 0 ].value;

Object.keys( map ).forEach(function( ico ) {
    // escape special characters for regex
    var icoE   = ico.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    // now replace actual symbols
    text       = text.replace( new RegExp(icoE, 'g'), map[ico] );
});

Example: http://jsfiddle/DBfpw/2/


Edit
In order to have a valid regular expression created, we need to escape ) and (

Note
The above snippet contains ECMAscript5 featured code. If you need to run that on legacy browsers, make sure to include a ES5 Shim library.

Note 2
Sorry the above code does not contain any jQuery code since its not necessary.

I would create an array of objects like:

var emoticons = [{regex: /:\)/g, image: "happy"},
                 {regex: /;\)/g, image: "wink"},
                 etc...]  

And then iterate over that array to make the replacements

for(var i = 0; i < emoticons.length; i++) {
    str = str.replace(emoticons[i].regex, 
        '<img src="/' + emoticons[i].image + '.jpg"/>');
}

You could use JavaScript to replace emoticons while user is typing. But to send the string with replaced emoticons to the server script is not good way. It is not safe way - anyone could replace your content on client side prior submission to the server side script. Saving <img src="images/sad.jpg"> instead of :-( or some replacement would be better. Less data to store + you can easier replace it with new image/image location and any other string.

So one way would be to post string to the server side script for storing in database. For view rendering (prior sending to browser) you can have function (something like below) that would replace each emoticon string to certain image:

<?php
    $text = 'Hey :-), how are you doing bro? Having some fun :-D? Lets meet :-(';

    $smileys = array(
        ':-)' => 'happy',
        ':-(' => 'sad',
        ':-D' => 'tongue'
    );

    foreach($smileys as $key => $value) { 
            $text =  str_replace($key, '<img srce="images/'.$value .'.jpg">', $text);
    }

    echo $text;
?>
// Start off by listing all supported emoticons and their names
var emoticons = {
    ":)": "smile",
    ":P": "tongue",
    ":(": "sad",
}, regex = [];

// push a regex for each one (:\)) onto an array.  Escape each special character
// each ponent is wrapped in unescaped parentheses to *capture* the token
// dynamically building this is optional -
// you may want to generate the regex once and use the literal
for(var emoticon in emoticons) {
    if(emoticons.hasOwnProperty(emoticon)) {
        regex.push("("+emoticon.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")+")");
    }
}

//join the array to form a string and use the regex OR operator.
regex = new RegExp(regex.join("|"), "g");
// Now the regex looks like this - /(:\))|(:P)|(:\()/g

// String replace function also takes a function as the second parameter.
// The function takes the captured text, (what we put in parenthesis earlier)
// and you can use it to refer to the emoticon hash at the beginning.
// Then you return the desired replaced text.
text = text.replace(regex, function(captured) {
    return "<img src='"+emoticons[captured]+".jpg'/>";
});

jsFiddle demo of this technique

发布评论

评论列表(0)

  1. 暂无评论