【问题标题】:Parse the content of a file and store in an object in JavaScript解析文件内容并存储在 JavaScript 中的对象中
【发布时间】:2014-10-15 08:24:28
【问题描述】:

我有一个测试文件“templates.txt”,我正在通过 ajax 调用加载它。

文本文件的内容就是这种格式。

{template templateA}
    templateA content
{/template}

{template templateB}   
    templateB content
{/template}

{template templateC}   
    templateC content
{/template}

当我通过 ajax 加载它时,我将整个文件的内容作为字符串获取。 假设我在变量 templateContent 中有文件的内容。

var templateContent = myFileContent;

但是我想解析这个字符串变量,并将其转换为对象,如下所示。

{ 
   templateA : templateA content,
   templateB : templateB content,
   templateC : templateC content
}

如何在 javascript 中做到这一点?正则表达式可以是一个不错的选择吗?

注意:此格式有要求。甚至 Google Closure 模板也使用相同的格式。 https://developers.google.com/closure/templates/docs/helloworld_js

【问题讨论】:

  • 为什么不构建 JSON 格式的文件内容?
  • 你的模板文件是那种奇怪的格式吗?你不能把它格式化成 JSON 格式吗?
  • @Moob 格式并不奇怪。有一个要求。甚至 google 闭包模板也使用相同的格式。查看链接developers.google.com/closure/templates/docs/helloworld_js
  • @hindmost 请检查已编辑的问题。

标签: javascript jquery regex


【解决方案1】:

我不会这样做,但如果您必须使用那种“奇怪”的格式,您可以使用 RegEx 将其拆分为多个部分:

/{template (.*?)}(.*?)\{\/template\}/g

注意,这假设您已经从模板字符串中删除了换行符,但您可以根据需要调整表达式。 Regex101 非常适合测试你的表情。

var obj = {},
    str = "{template templateA}templateA content{/template}{template templateB}templateB content{/template}{template templateC}templateC content{/template}",
    rx = /{template (.*?)}(.*?)\{\/template\}/g,
    item;

while (item = rx.exec(str))
    obj[item[1]] = item[2];

console.log(obj);
alert(JSON.stringify(obj)); //outputs {"templateA":"templateA content","templateB":"templateB content","templateC":"templateC content"}

【讨论】:

    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多