Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Function required to replace content in a String

Tags:

javascript

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

like image 439
Adam Avatar asked Nov 17 '12 02:11

Adam


2 Answers

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.net/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.

like image 55
jAndy Avatar answered Oct 17 '22 05:10

jAndy


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"/>');
}
like image 35
Samuel Rossille Avatar answered Oct 17 '22 05:10

Samuel Rossille