yevg yevg - 1 year ago 57
Javascript Question

Concatenating string inside javascript object definition

Im trying to put together a regex router that includes an arbitrary number of slugs and key-values.

Im doing this by creating an object of patterns and their respective modules and will then match the regex to the module.

But Javascript throws an error when I use the "+" operator to concatenate strings inside of the object definition.

var SLUG ='\/[a-z|A-Z|0-9|-]+)([\/]{0,1})?';
var KEYS ='\/?(\?.*)?$/';

var routes = {

'\/public\/images' + KEYS : 'images', /* <-- ERROR: '+' Unexpected token */
'\/public\/other' + SLUG + KEYS : 'something-else',


Why is this error being thrown and how can I concatenate these values outside of storying them in separate variables?

Answer Source

var SLUG = '\/[a-z|A-Z|0-9|-]+)([\/]{0,1})?';
var KEYS = '\/?(\?.*)?$/';

var routes = {};

function addRoute(keyParts, value){
  routes[keyParts.join('')] = value;

addRoute(['\/public\/images', KEYS], 'images');
addRoute(['\/public\/other', SLUG, KEYS], 'something-else');


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download