Timothy Clyne Jr Timothy Clyne Jr - 4 months ago 9
Javascript Question

How to find if a string contains a word between two colons, then return that result including the colons

I'm writing a bot for Discord, and I want to be able to detect if a string contains a substring that is in the format

:smilie:
, for example

"I am so excited for this video game! :getin:".

Currently the way I have it set up, if a user posts a separate message, ie.

I am so excited for this video game!

:getin:

my bot will attach the smilie by using this algorithm

case startsWith(message, ":"):
channel.uploadFile("saemotes/"+message+".png");
channel.uploadFile("saemotes/"+message+".gif");
break;


This works fine, however I would like it to be more elegant. All image files for the emotes are named
:smilie_name:.png/.gif
depending on what it is, so based on that, what would be the best regex expression to pull the potential file name out of a string? I'm assuming it would be something like

case S(message).match(/\b:smilie_name:\b/) !== null:
smilie_name_parsed_from_regex = <regex_result>;
channel.uploadFile("saemotes/"+<smilie_name_parsed_from_regex>+".png");
channel.uploadFile("saemotes/"+<smilie_name_parsed_from_regex>+".gif");
break;


Any help would be appreciated, thanks!

Answer

Seems like a minor alteration to your regex should do the trick:

case /:([\w]+):/g.test(S(message)) === true:
    var images = S(message).match(/:([\w]+):/g);
    // map matches into urls and upload
    images.map(function(image) {
       return 'saemotes/'+image.replace(/:/g, '')+'.png';
    }).forEach(channel.uploadFile);
break;