简体   繁体   中英

Looking for the exact opposite of path-to-regexp

I am building some API connector, and I'd like to be able to generate fetch URL easily.

My idea is to base my solution on the path-to-regexp lib syntax, so that for exemple injectParams('/foo/:hello', { hello: 'world'}) return '/foo/world

Is there an existing library to do such an injection ?

Here I'm replacing each key (having prefix :) with it's value in path variable.

 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', { "ab": 'world'}) console.log( result );

This will replace all occurrences of :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

How it works

/:\\w+/g find all :keys.
.replace(/:\\w+\\??/g, x => ... result of searching for /:\\w+\\??/g is passed to function and it has to decide with with value it should be replaced.
...obj[x.replace(':','')]) extract key value from object

path-to-regexp目前已编译api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM