SteeveDroz SteeveDroz - 1 month ago 5
JSON Question

How can I use JSON keys as regex?

I would like to have the following JSON object:

let emotes = {
/:-?\)/: 'smiley.png',
/:-?\(/: 'sady.png',
/:-?o/i: 'surprisey.png'
}


And I would like to replace the keys by the values in a text like this:

Object.keys(emotes).forEach(function(emote) {
content = content.replace(emote, '<img src="smileys/' + emotes[emote] + '">')
})


This is not working. What is the correct way to do that?

Answer

Personally I would use an array. That allows you to use regex constants and avoid constructing RegExp instances from strings, and it also would guarantee the application order:

let emotes = [
  [ /:-?\)/, 'smiley.png' ],
  [ /:-?\(/, 'sady.png' ],
  [ /:-?o/i, 'surprisey.png' ]
];

Then:

emotes.forEach(function(pair) {
  content = content.replace(pair[0], '<img src="smileys/' + pair[1] + '">');
});

You could use an array of objects if you didn't want the (slight, in my opinion, but to each his own) ugliness of the numeric indexes:

let emotes = [
  { pattern: /:-?\)/, src: 'smiley.png' },
  { pattern: /:-?\(/, src: 'sady.png' },
  { pattern: /:-?o/i, src: 'surprisey.png' }
];
Comments