我有这样的字符串:
const a = '/example/:someItemUuid/hello'
const b = '/example/:someItemUuid/hello/:otherItemUuid'
const params = {
someItemUuid: '12345',
otherItemUuid: '67890'
}
我正在寻找一种简单的方法来通过:
buildUrl(a, params)
并获取 /example/12345/hello
buildUrl(b, params)
并获取 /example/12345/hello/67890
是否有一个简单的方法库可以做到这一点,或者使用lodash的简单方法?
最佳答案
您无需拆分和加入。您可以使用替换及其回调
const a = '/example/:someItemUuid/hello'
const b = '/example/:someItemUuid/hello/:otherItemUuid'
const params = {someItemUuid: '12345',otherItemUuid: '67890'}
let replaceValues = (str,params) =>
str.replace(/(^|\/):(\w+)(?=\/|$)/g, (m, g1, g2) => g1 + (params[g2] || m))
console.log(replaceValues(a,params))
console.log(replaceValues(b,params))
如果您的环境也支持lookbehind,那么您可以使用
`(?<=^|\/):(\w+)(?=\/|$)
关于javascript - 替换所有以冒号开头的字符串,例如快速路由路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58636492/