寻找路径到正则表达式的完全相反

时间:2017-02-10 16:46:54

标签: javascript regex routes

我正在构建一些API连接器,并且我希望能够轻松生成提取URL。

我的想法是将我的解决方案基于path-to-regexp lib语法,以便例如injectParams('/foo/:hello', { hello: 'world'})返回'/foo/world

是否有现有的库可以进行这样的注射?

3 个答案:

答案 0 :(得分:2)

这里我用路径变量中的值替换每个键(有前缀:)。

function injectParams( path , obj )
{
    for( var key in obj ){
      var rgx = new RegExp(':' + key + '\\b', 'g');
      path = path.replace( rgx, obj[key] );
    }
  return path;
}
var result;
result = injectParams('/foo/:hello', { hello: 'world'})
console.log( result );
// prints  "/foo/world" in console 

result  = injectParams('/foo/:hello/:another', { hello: 'world',another:'wroking'});
console.log( result );
//   prints  "/foo/world/workng" in console

result  = injectParams('/foo/:hello/:another/:hello/:hello', { hello: 'world',another:'wroking'});
console.log( result );
//   prints "/foo/world/wroking/world/world"

result = injectParams('/foo/:a-b', { "a-b": 'world'})
console.log( result );

答案 1 :(得分:1)

这将替换所有出现的:key

const injectParams = (path, obj) =>
  path.replace(/:\w+\??/g, x => {
      const val = obj[x.replace(/:|\?/g, '')]
      if(val != undefined) return val
      else if (/\?/.test(x)) return ''
      else throw new Error(`Value for '${x}' not specified.`)
  })

  console.log(injectParams('http://stackoverflow.com/:post?', {}))
  console.log(injectParams('http://stackoverflow.com/:post?', {post: 1}))
  console.log(injectParams('http://stackoverflow.com/:post', {})) // throw error

如何运作

/:\w+/g找到所有:键。
搜索.replace(/:\w+\??/g, x => ...的{​​{1}}结果会传递给函数,并且必须使用值来决定它应该被替换。
/:\w+\??/g从对象中提取键值

答案 2 :(得分:0)

path-to-regexp 目前有 compile api