如何将哈希模式映射到字符串值?

时间:2012-11-26 14:37:25

标签: javascript regex

我想将位置哈希中的内容映射到字符串。映射必须基于下面的模式(:占位符是任意数字,也许是RegEx?)。在函数中处理这个问题的最佳方法是什么?

    'news/:NewsID/dup' => 'newsDuplicate',
    'news/:NewsID' => 'newsDetail',
    'news/:NewsID/authors' => 'authorsList',
    'news/:NewsID/authors/' => 'authorsList',
    'news/:NewsID/authors/create' => 'authorsCreate',
    'news/:NewsID/authors/:AuthorID' => 'authorDetail',
    'news/:NewsID/authors/:AuthorID/orders' => 'orders',
    'news/:NewsID/authors/:AuthorID/workflow' => 'workflow',
    'news/:NewsID/authors/:AuthorID/tags' => 'tags'

我想在导航中突出显示正确的按钮,并想要一个像handleNav()这样的函数,它会根据模式突出显示右键。

例如,在http://mydomain.com#!news/123/authors/987时,我可以这样做:

function handleNav() {
  var current = ?? //get mapped string above
  $('button.' + current).addClass('active').siblings().removeClass('active');
}

如何根据映射获取上面的“当前”变量?不确定是否有一堆if-else语句是最好的方式而且我不太了解正则表达式。感谢您的帮助或见解。

1 个答案:

答案 0 :(得分:0)

也许在读取映射之前规范化字符串?像这样:

var map = {
  'news/ID/dup' : 'newsDuplicate',
  'news/ID' : 'newsDetail',
  'news/ID/authors' : 'authorsList',
  'news/ID/authors/' : 'authorsList',
  'news/ID/authors/create' : 'authorsCreate',
  'news/ID/authors/:AuthorID' : 'authorDetail',
  'news/ID/authors/:AuthorID/orders' : 'orders',
  'news/ID/authors/:AuthorID/workflow' : 'workflow',
  'news/ID/authors/:AuthorID/tags' : 'tags'
}

function normalize(str) {
    return str.replace(/news\/\d+/,'news/ID')
}

var current = map[normalize(url)];