Skip to content

添加一个新的解法 #117

Open
Open
@chouchouji

Description

@chouchouji

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" 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions