-1

I would like to edit javascript from this post and use regexp inside map, if possible: like string starts with "xyz", but that syntax is not working for me :

var anchorMap = {
    "A": "/products/A",
    "B": "/products/B",
    /^xyz: "/products/xyz"
}

is that possible ? Or what is the easiest way to implement such logic ?

mauek unak
  • 702
  • 2
  • 11
  • 28
  • 2
    I'm sure this will help you! https://stackoverflow.com/questions/7365027/how-to-use-a-regexp-literal-as-object-key – Kashmir54 Feb 22 '19 at 09:48

2 Answers2

0

That's not something I would recommend (and I don't really understand your goal here - however, you could make the regex a string and loop the keys to test against.

var anchorMap = {
    "A": "/products/A",
    "B": "/products/B",
    "^.{3}": "/products/xyz"
};

const k = Object.keys(anchorMap).find(e => new RegExp(e).test("xyz"));
console.log(anchorMap[k]);
baao
  • 71,625
  • 17
  • 143
  • 203
0

You can define keys as regex and than using find you can see which regex key it is matching and get the value for that particular key from object.

var anchorMap = {
    "A": "/products/A",
    "B": "/products/B",
    [`^xyz`]: "/products/xyz"
}

let str = 'xyz'

let op = Object.keys(anchorMap).find( e => new RegExp(e).test(str))

console.log(anchorMap[op])
Code Maniac
  • 37,143
  • 5
  • 39
  • 60