js如何提取字符串中的对象?

用nodejs读取了另一个js文件,得到该js文件的字符串,内容如下。


window.config = {  
    baseUrl: 'http://192.168.1.100',  
    describe: '生产环境'  
};

如何获取到里面的对象内容,像下面这样。

{  
    baseUrl: 'http://192.168.1.100',  
    describe: '生产环境'  
}
已解决 悬赏分:50 - 解决时间 2021-11-26 16:33
反对 0举报 0 收藏 0

回答2

最佳
  • @
    const str = `
    
    window.config = {  
        baseUrl: 'http://192.168.1.100',  
        describe: '生产环境'  
    };
    `
    const re = /{[\S\s]*}/;
    const match = str.match(re);
    if(match){
    eval('var obj =' + match[0])
    console.log(obj)
    }
    
    
    支持 0 反对 0 举报
    2021-11-26 08:42
  • @

    字符串转对象: JSON.parse(str)

    支持 0 反对 0 举报
    2021-11-26 08:51