Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加一个新的解法 #117

Open
chouchouji opened this issue Oct 14, 2024 · 0 comments
Open

添加一个新的解法 #117

chouchouji opened this issue Oct 14, 2024 · 0 comments

Comments

@chouchouji
Copy link

Post link

js 匹配 url 路径参数,并替换变量

Resolution

想了一种不用正则的解法

function replaceUrl(url: string, target: Record<string | number, string | number>) {
    let res = ''
    const length = url.length
    let key = ''
    let shouldBeCollected = false

    for (let i = 0; i < length; i++) {
        if (url[i] === '{') {
            shouldBeCollected = true
            continue
        }
        if (url[i] === '}') {
            res += target[key]
            shouldBeCollected = false
            key = ''
            continue
        }
        if (shouldBeCollected) {
            key += url[i]
        } else {
            res += url[i]
        }
    }
    return res
}

console.log(replaceUrl('/yearpost/settop/{1}/{num}/1', { 1: 222, 'num': 444 })) // "/yearpost/settop/222/444/1"

console.log(replaceUrl('/yearpost/settop/{id}/1', { id: 'test01' }))  // "/yearpost/settop/test01/1" 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant