使用正则表达式,把带有{}的字符串转为一个对象

220 阅读1分钟

例如字符串如下:

const str = `wx.config({
    debug: false,
    appId: 'xxxxxx,
    timestamp: 'xxxxxx',
    nonceStr: 'xxxxxx',
    signature: 'xxxxxx',
    href: 'xxxxxx',
    jsApiList: ['xxxxxx','xxxxxx','xxxxxx','xxxxxx','xxxxxx','xxxxxx','xxxxxx','xxxxxx'],
    openTagList: ['xxxxxx']
});`

1.使用正则表达式方法replace替换,match截取

const objStr = str.replace(/\s+/g, "").match(/\{(.+?)\}/g)[0]

2.因为不是标准的json格式字符串,所以无法使用JSON.parse来转化,但是可以使用eval来把字符串转为js代码

const obj = eval("(" + objStr + ")")
{
    "debug": false,
    "appId": "xxxxxx",
    "timestamp": "xxxxxx",
    "nonceStr": "xxxxxx",
    "signature": "xxxxxx",
    "href": "xxxxxx",
    "jsApiList": [
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx"
    ],
    "openTagList": [
        "xxxxxx"
    ]
}

3.如果不使用eval的话,也可以使用new Function()

const obj = new Function(`return ${objStr}`)()
{
    "debug": false,
    "appId": "xxxxxx",
    "timestamp": "xxxxxx",
    "nonceStr": "xxxxxx",
    "signature": "xxxxxx",
    "href": "xxxxxx",
    "jsApiList": [
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx",
        "xxxxxx"
    ],
    "openTagList": [
        "xxxxxx"
    ]
}

也是同样的效果!