0

I'm trying to add emoticons to my web-based chat site, and trying to use RegExp to do it.

It works under some circumstances, but not others, and it's driving me crazy.

The emoticons are stored in a database - I pull them out via AJAX json and work through the resulting array, replacing as it goes. Here's what the response looks like via the F12 Dev tools :

arrayVisual

When the emoticon.SymbolShortcut value is set to ':D', it works, but does not work for ':('.

The problematic emoticon object contains :

emoticon.FileLocation = '<i class="material-icons emoticon" style="font-size:16x;">sentiment_very_satisfied</i>' //I know this isn't a file location - bad object naming :)

emoticon.SymbolShortcut = ':('

var sMarkup;
var strRegEx = '';

var pText ='some text :('

$.each(emoticonArray, function (index, emoticon) {
    strRegEx = emoticon.SymbolShortcut.replace(')', '[)]').replace('(', '[(]');

    var regEx = new RegExp(strRegEx, "gi");

    pText = pText.replace(strRegEx, emoticon.FileLocation);

});

So in summary, the issue is the replace doesn't work for the ':(' char combination, but does work with ':D'.

I expect the characters in the pText variable ':(' to be replaced with 'sentiment_very_satisfied', but all I get back is the same string I handed in, with no replacement made

Thanks in advance - all and any suggestions are welcomed. Please shoutout if I can provide any more information to get this most frustrating puzzle solved.

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
Melbfella
  • 11
  • 1
  • 5
  • 1
    What is the problem you are having? "Failing", "doesn't work" are not helpful. How does that work? What do you expect? Please provide an [MCVE (minimal complete verifiable example)](http://stackoverflow.com/help/mcve). – Wiktor Stribiżew Apr 08 '18 at 09:40
  • Hi Wiktor, The issue is the replace doesn't work for the ':(' char combination, but does work with ':D'. I expect the characters in the pText variable ':(' to be replaced with 'sentiment_very_satisfied', but all I get back is the same string I handed in, with no replacement made. – Melbfella Apr 08 '18 at 09:41
  • Try escaping special chars with https://stackoverflow.com/a/3561711/3832970 – Wiktor Stribiżew Apr 08 '18 at 09:46
  • @Melbfella why are you `'some text :(' strRegEx = emoticon.SymbolShortcut.replace(')', '[)]').replace('(', '[(]');` doing this ? – Mustofa Rizwan Apr 08 '18 at 09:47

1 Answers1

-1

Updated The answer while keeping OP's flow into consideration:

var pText ='some text :('

strRegEx = `:(`.replace(')', '\\)').replace('(', '\\(');
var regEx = new RegExp(strRegEx, "i");
pText = pText.replace(regEx,`<i class="material-icons emoticon" style="font-size:16x;">sentiment_very_satisfied</i>`);
console.log(pText);
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
  • I guess the downvote is for not explaining the working of the regex, but the answer seems pretty clear to me. – Robo Mop Apr 08 '18 at 10:20