简体   繁体   English

替换所有以冒号开头的字符串,例如快速路由路径

[英]Replace all strings beginning with colon like express route path

I have strings like this:我有这样的字符串:

const a = '/example/:someItemUuid/hello'
const b = '/example/:someItemUuid/hello/:otherItemUuid'

const params = {
  someItemUuid: '12345',
  otherItemUuid: '67890'
}

I am looking for a simple way to pass:我正在寻找一种简单的通过方式:

buildUrl(a, params) and get /example/12345/hello buildUrl(a, params)并获取/example/12345/hello

buildUrl(b, params) and get /example/12345/hello/67890 buildUrl(b, params)并获取/example/12345/hello/67890

Is there a simple way library that exists that does this, or a simple way using lodash?是否有一个简单的方法库可以做到这一点,或者使用 lodash 的简单方法?

You need not to split and join.您无需拆分和加入。 You can use replace and it's callback您可以使用替换它的回调

在此处输入图像描述

 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))


If your environment supports lookbehind also then you can use如果您的环境也支持lookbehind,那么您可以使用

`(?<=^|\/):(\w+)(?=\/|$)
  const fullLink = page.split('/').map(i => {
    if (i.match(/^:/)) return camelizePayload[i.replace(/^:/, '')]
    return i
  }).join('/')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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