适配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 (like1in/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 (
-).
- Starts and ends with a lowercase letter (
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
相关产品推荐
相关产品推荐

