0

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

I'm 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 storing them in separate variables?

4
  • Object must have a property name and a value assigned to it. You can access the value in a object by its property. That is what you are missing Commented Nov 17, 2016 at 2:32
  • the property names are supposed to be the concatenated strings and the values would be the modules (images, etc) Commented Nov 17, 2016 at 2:37
  • 1
    Oh ya .. I overlooked it. You just need to use the [ ] to add property values then . Like just have a routes plain object like routes= {} then you can do routes[ your concatenation logic] = 'images'; Commented Nov 17, 2016 at 2:40
  • ah! yes. perfect. I guess I was trying to do it all in the declaration. thank you! Commented Nov 17, 2016 at 2:45

3 Answers 3

2

// 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);

Sign up to request clarification or add additional context in comments.

Comments

1

How about this solution. Hope it helps!

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

function obj(){
    obj=new Object();
    this.add=function(key,value){
        obj[key]=value;
    }
    this.obj=obj
}

routes=new obj();
routes.add(['\/public\/images'+ KEYS], 'images');
routes.add(['\/public\/other' + SLUG + KEYS],'something-else');

console.log(routes.obj);

1 Comment

What is the reason for doing ""+key+""? Why are you creating a new object inside the constructor when you could just say this.add = function(key, value) { this[key] = value; }?
0

Use computed property names:

var routes = {
  [`\/public\/images${KEYS}`]: 'images',

The above also uses ES6 template literals.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.