字符串解析{{var}} / text {{var}}

时间:2018-07-19 08:46:46

标签: javascript regex parsing

我需要解析跟随字符串const input = '{{var}}/text{{var}}'的结果必须跟随 const result = ['{{var}}', '/text', '{{var}}']。谢谢

1 个答案:

答案 0 :(得分:0)

您将需要一个函数来替换文本,但我认为您想要的正则表达式为({{\w+}})(\/\w+)({{\w+}})。这提供了1-3组中的部分,因此您可以按自己的喜好格式化它们。您可能还想添加检查以确保第1部分与第3部分相同,以避免配对不匹配。

function replace(str) {
    let matches = str.match(/({{\w+}})(\/\w+)({{\w+}})/);
    return str.replace(/({{\w+}})(\/\w+)({{\w+}})/, `['${matches[1]}', '${matches[2]}', '${matches[3]}']`);
}
replace("const input = '{{var}}/text{{var}}'"); // "const input = '['{{var}}', '/text', '{{var}}']'"
相关问题