JavaScript实现:将搜索URL中{}内字符串转为查询参数的问题
Solution for Converting URL Path Variables to Query Parameters
Great question! The core issue with your original code is that the greedy regex {(.*)} captures everything between the first { and last } in multi-variable patterns. Let's fix that with a more targeted approach that handles multiple variables, different separators (like -, /, _), and preserves existing query parameters.
Step-by-Step Explanation
- Extract Variable Names: Use a global regex to capture all
{variable}placeholders from the user-provided format string. - Generate Path Matching Regex: Convert the format string into a regex that can capture the actual values from the target URL, preserving separators like
-,/, or_. - Capture Variable Values: Match the target URL's path against the generated regex to get the values corresponding to each variable.
- Build New URL: Construct the new base path (removing the variable-containing segment), convert variables to query parameters, and append any existing query parameters.
Complete Code Implementation
// Example inputs var search_url_format = '/search/{city}-{service}'; // User-provided format var urloutput = '/search/newyork-gyms?dev=desktop&id=1220391131'; // Target URL // Test other formats by uncommenting below: // var search_url_format = 'search/{city}/{service}/'; // var urloutput = 'search/london/restaurants/?dev=mobile'; // var search_url_format = 'search-{country}'; // var urloutput = 'search-germany'; console.log(URL2Query(search_url_format, urloutput)); function URL2Query(format, targetUrl) { // Split target URL into path and existing query parameters const [path, existingQuery] = targetUrl.split('?'); const queryParams = new URLSearchParams(existingQuery || ''); // Extract all variable names from the format string const variableMatches = format.match(/{([^}]+)}/g); if (!variableMatches) return targetUrl; // No variables found, return original URL const variables = variableMatches.map(match => match.slice(1, -1)); // e.g., ['city', 'service'] // Generate regex pattern to match the path and capture variable values // Escape special regex characters in the format, then replace {var} with capture groups const escapedFormat = format.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regexPattern = escapedFormat.replace(/{[^}]+}/g, '([^\\/?&]+)'); const pathRegex = new RegExp(`^${regexPattern}`); // Match the path to get variable values const pathMatch = path.match(pathRegex); if (!pathMatch) return targetUrl; // Path doesn't match format, return original const variableValues = pathMatch.slice(1); // e.g., ['newyork', 'gyms'] // Add variables as query parameters variables.forEach((varName, index) => { queryParams.set(varName, variableValues[index]); }); // Build the new base path (remove the variable segment from the format) const basePath = format.split('{')[0].replace(/[-_\/]$/, ''); // e.g., '/search' // Construct the final URL const finalQuery = queryParams.toString(); return finalQuery ? `${basePath}?${finalQuery}` : basePath; }
Key Features
- Multi-Variable Support: Handles patterns like
/search/{city}-{service},search/{city}/{service}/, orsearch_{country}seamlessly. - Preserves Existing Query Parameters: Keeps parameters like
dev=desktoporid=1220391131intact. - Robust Matching: Uses non-greedy regex to capture individual variables and escapes special characters to avoid regex errors.
- Fallback Handling: Returns the original URL if the path doesn't match the format or no variables are found.
Test Cases
Multi-variable with
-separator:- Input format:
/search/{city}-{service} - Target URL:
/search/newyork-gyms?dev=desktop&id=1220391131 - Output:
/search?city=newyork&service=gyms&dev=desktop&id=1220391131
- Input format:
Multi-variable with
/separator:- Input format:
search/{city}/{service}/ - Target URL:
search/london/restaurants/?dev=mobile - Output:
search?city=london&service=restaurants&dev=mobile
- Input format:
Single-variable case:
- Input format:
search-{country} - Target URL:
search-germany - Output:
search?country=germany
- Input format:
内容的提问来源于stack exchange,提问作者Ritwikga
相关产品推荐
相关产品推荐

