如何在JavaScript中实现Golang strconv.Quote功能以修复YAML解析问题
在JavaScript中实现Golang strconv.Quote功能以修复YAML转义问题
你遇到的问题是原YAML中path字段包含未转义的引号和特殊字符,导致yaml-ast-parser解析失败。Golang的strconv.Quote通过对字符串添加双引号并转义特殊字符解决了这个问题,下面是在JavaScript中实现等价功能的方案:
核心实现函数
这个函数会模拟strconv.Quote的行为:用双引号包裹字符串,同时转义双引号、反斜杠以及常见控制字符,生成符合YAML规范的字符串:
function strconvQuote(str) { // 先转义反斜杠,避免后续转义操作破坏已有反斜杠 let escapedStr = str.replace(/\\/g, '\\\\'); // 转义双引号 escapedStr = escapedStr.replace(/"/g, '\\"'); // 转义常见控制字符 escapedStr = escapedStr.replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t') .replace(/\b/g, '\\b') .replace(/\f/g, '\\f'); // 用双引号包裹最终结果 return `"${escapedStr}"`; }
测试示例
将你提供的原path值传入函数:
const originalPath = 'site:^example\\.com?"something"..."something"'; const quotedPath = strconvQuote(originalPath); console.log(quotedPath); // 输出结果:"site:^example\\.com?\"something\"...\"something\""
这个结果和Golangstrconv.Quote处理后的完全一致,能被yaml-ast-parser正确解析。
扩展支持(可选)
如果需要处理不可打印的ASCII字符(如0x00-0x1F、0x7F),可以在函数中添加Unicode转义逻辑:
function strconvQuote(str) { let escapedStr = str.replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t') .replace(/\b/g, '\\b') .replace(/\f/g, '\\f'); // 转义不可打印ASCII字符为\uXXXX格式 escapedStr = escapedStr.replace(/[\x00-\x1F\x7F]/g, char => { const code = char.charCodeAt(0); return `\\u${code.toString(16).padStart(4, '0')}`; }); return `"${escapedStr}"`; }
使用方式
在生成YAML内容时,对path字段的值调用这个函数即可,比如:
const yamlContent = `--- body: "something else" path: ${strconvQuote('site:^example\\.com?"something"..."something"')} title: "How to do this"`;
生成的YAML内容完全符合规范,可正常被yaml-ast-parser解析。
内容的提问来源于stack exchange,提问作者proton
相关产品推荐
相关产品推荐

