正则表达式+replace的一些用法

95 阅读1分钟

foo=1&foo=2&blah=a&blah=b&foo=3 => foo=1,2,3&blah=a,b

正则表达式: /([^&=]+)=([^&]*)/g


function compress(source) {
    const keys = {}
    source.replace(/([^&=]+)=([^&]*)/g, function (all, key, value) {
        keys[key] = keys[key] ? keys[key] + ',' + value : value
        return ''
    })
    
    const result = []
    for (let key in keys) {
        result.push(key + '=' + keys[key])
    }
    return result.join('&')
}

abc-def -> abcDef

source.replace(/-([a-z])/ig, function (all, value) {
    return value.toUpperCase()
})

abcDef -> abc-def

source.replace(/(?:[a-z])([A-Z])/g, function (all, value) {
    return all[0] + '-' + value.toLocaleLowerCase()
})