@cc-heart/utils
Version:
🔧 javascript common tools collection
33 lines (31 loc) • 903 B
text/typescript
/**
* convert query string to object
*
* @param url http url
* @returns
*/
export function convertQueryString<T extends Record<string, string>>(
url: string,
): T {
const query = url.split('?')[1]
const result = {} as T
if (query) {
query.split('&').forEach((item) => {
const [key, value] = item.split('=')
Reflect.set(result, key, decodeURIComponent(value))
})
}
return result
}
/**
* convert params routes to regular expressions
*
* @param path a params paths
* @returns null or An array contains the RegExp that matches the params and the path for each params parameter
*/
export function convertParamsRouterToRegExp(path: string) {
const matcher = path.match(/:(.*?)(?:\/|$)/g)
if (matcher === null) return null
const reg = new RegExp(path.replace(/:(.*?)(\/|$)/g, '.*?$2'))
return [reg, matcher.map((val) => val.replace(/:(.*?)(\/|$)/g, '$1'))]
}