2014-10-15 3 views
-3

나는 ajax 호출을 통해로드하는 'templates.txt'파일을 가지고 있습니다.파일의 내용을 구문 분석하고 JavaScript의 객체에 저장하십시오.

텍스트 파일의 내용은이 형식입니다.

{template templateA} 
    templateA content 
{/template} 

{template templateB} 
    templateB content 
{/template} 

{template templateC} 
    templateC content 
{/template} 

아약스를 통해로드 할 때 전체 파일의 내용을 문자열로 가져옵니다. 변수 templateContent에 파일 내용이 있다고 가정합니다.

var templateContent = myFileContent; 

하지만이 문자열 변수를 구문 분석하고 다음과 같이 개체로 변환하고 싶습니다.

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

어떻게 자바 스크립트로 할 수 있습니까? regex는 좋은 옵션이 될 수 있습니까?

참고 :이 형식이 필요합니다. Google Closure 템플릿도 동일한 형식을 사용합니다. https://developers.google.com/closure/templates/docs/helloworld_js

+2

왜 JSON 형식으로 파일의 내용을 구축하지? – hindmost

+1

템플릿 파일이 그 이상한 형식으로되어있는 reaon이 있습니까? 그냥 JSON으로 포맷 할 수 없습니까? – Moob

+0

@Moob 형식이 이상하지 않습니다. 요구 사항이 있습니다. Google 클로저 템플릿에서도 동일한 형식을 사용합니다. https://developers.google.com/closure/templates/docs/helloworld_js 링크를 확인하십시오 – Aniket

답변

1

그것은 내가 그것에 대해 가고 싶어하지만 당신은이 경우 '이상한'형식이 부분으로 분할 정규식을 사용할 수 있다는 것을 사용하는 방법이 아니다 :

/{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"}

관련 문제