【问题标题】:JavaScript Regex find and replace multiple word with multiple word without using multiple replace functionJavaScript 正则表达式在不使用多个替换功能的情况下用多个单词查找和替换多个单词
【发布时间】:2020-07-30 14:08:36
【问题描述】:

我正在使用 Angular7,我想更改环境文件中定义的 url 而无需串联。

所以我的组件中有一个这样的字符串。

"upload/document/:orgId/products/:productId"

我想用 2 个 id 替换它,只使用正则表达式,这样我就可以得到这样的输出。我不想使用多个替换调用。

 "/upload/document/101/products/99101"

提前致谢!

【问题讨论】:

  • const replaced = "upload/document/:orgId/products/:productId".replace(":orgId", 101).replace(":productId", 99101);
  • 感谢您的快速响应,但我想在正则表达式中执行此操作,例如 str.replace(re, "$2, $1"

标签: javascript regex angular typescript


【解决方案1】:

var template = "upload/document/:orgId/products/:productId";

var result = template.replace(/:orgId\b/, '101').replace(/:productId\b/, '99101');

console.log(result);

【讨论】:

  • 感谢您的快速响应,但我想在正则表达式中执行类似 str.replace(re, "$2, $1")
  • 这是正则表达式。 /:orgId\b//:productId\b/ 是正则表达式的示例。如果您在谈论 $1$2 等,这些是捕获组中必须显示在结果字符串中的内容的替换。但是,您的问题不需要捕获组。您可以使用它们,但是为了使用特定工具,您最终会得到一个更复杂的解决方案。您必须使用捕获组吗? (比如,这是作业还是什么?)
【解决方案2】:

经过一番艰苦的考验和考验,这是可以实现的。虽然它不是我想要的一次调用,但它正在执行所有必需的操作。

let baseUrl= "upload/document/:orgId/products/:productId";
let mapper = {
               ':orgId': 101, 
               ':productId': 99101 
             };
let newUrl = baseUrl.replace(
                 /:orgId|:productId/gi, 
                 matched => mapper[matched]
             ) ;
console.log(newUrl);

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 2012-10-27
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多