You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适配JSON API规范的URL路径参数替换正则表达式需求

Solution

To fix the issue where UUIDs and numeric IDs weren't being replaced with *, we need to adjust the regex to exclude parameter formats (UUIDs, pure numbers) while still matching valid JSON API resource member names.

Updated Regex

/^(?!([0-9]+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$)[a-z][a-z0-9-]*[a-z]$/

Breakdown of the Regex

Let's break down how this works:

  • ^ and $: Anchor the match to the start and end of the string, ensuring we check the entire path segment.
  • (?!...): Negative lookahead to exclude two common parameter types:
    • [0-9]+: Matches pure numeric IDs (like 1 in /user/1).
    • [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}: Matches standard UUID formats (with the 8-4-4-4-12 hex character structure).
  • [a-z][a-z0-9-]*[a-z]: Enforces the core JSON API resource member rules:
    • Starts and ends with a lowercase letter (a-z).
    • Contains only lowercase letters, numbers, and hyphens (-).

Modified Function

Replace your existing REGEX.JSONAPI_RESOURCE_MEMBER with the new regex in the escape function:

// Define the updated regex
const REGEX = {
  JSONAPI_RESOURCE_MEMBER: /^(?!([0-9]+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$)[a-z][a-z0-9-]*[a-z]$/
};

const escapeResourcePathParameters = resource => resource
  .substr(resource.startsWith('/') ? 1 : 0)
  .split('/')
  .reduce((url, member) => {
    const match = member.match(REGEX.JSONAPI_RESOURCE_MEMBER);
    const part = match ? member : '*';
    return `${url}/${part}`;
  }, '');

Test with Your Examples

Let's verify this works with your sample URLs:

  • Input: /user/e09e4f9f-cfcd-4a23-a88f-b9f2f265167f/info → Output: /user/*/info
  • Input: /user/e09e4f9f-cfcd-4a23-a88f-b9f2f265167f → Output: /user/*
  • Input: /user/1 → Output: /user/*

All cases now produce the expected results: UUIDs and numeric IDs are correctly identified as parameters and replaced with *, while valid resource names like user and info are preserved.

内容的提问来源于stack exchange,提问作者Vladyslav Sheruda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:22:21