yevg yevg - 15 days ago 6
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.

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

// ROUTES
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

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

// ROUTES 
var routes = {};

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

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

console.log(routes);

Comments