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

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

/*  
 * @Description: 生产环境  
 * @Author: xxx@163.com  
 */
window.config = {  
    baseUrl: 'http://192.168.1.100',  
    describe: '生产环境'  
};

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

{  
    baseUrl: 'http://192.168.1.100',  
    describe: '生产环境'  
}
阅读 5k
2 个回答
const str = `
/*  
 * @Description: 生产环境  
 * @Author: xxx@163.com  
 */
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)
}

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题