Skip to content

Latest commit

 

History

History
46 lines (34 loc) · 1.25 KB

parseStr.md

File metadata and controls

46 lines (34 loc) · 1.25 KB
标题 标签
parseStr(解析字符串) string,parse(字符串,解析)

解析字符串。

  • 使用try..catch语句处理解析失败的场景。
  • 使用 JSON.parse或者模拟实现一个eval方法来解析传入的字符串。
  • 第二个参数 type 可以指定解析的类型,默认为 json,值仅有json/eval。
const parseStr = (str, type = 'json') => {
    const parseMethod = {
        'eval': (v) => new Function(`return ${v}`)(),
        'json': JSON.parse
    }
    let res = null;
    try {
        const method = parseMethod[type];
        if(method){
            res = method(str);
        }
    } catch (error) {
        console.error(`[parse data error]:${error}`);
    }
    return res;
}

ts代码如下:

调用方式:

应用场景

结果如下:

<iframe src="codes/javascript/html/parseStr.html"></iframe>