제품을 설명하는 색상 및 브랜드와 같은 속성이 무수히 많은 객체가 있습니다. 나는 단락 형태로 제품 설명을 동적으로 생성하는 방법을 찾고 있는데 (API가 제공하지 않기 때문에), 괄호 안에 "소품"이있는 "템플릿"을 작성하는 방법을 생각해 냈다 {{}}
. 필자는 "props"를 키 값으로 대체하여 문자열에 객체 속성을 주입하여 템플릿을 "파싱"하는 함수를 작성했습니다. 예를 들어JavaScript : .exec()와 연속 일치 찾기
:
대상 : {color: 'white'}
템플릿 : "The bowl is {{color}}."
결과 : "The bowl is white."
어떤 이유
, 내 구문 분석 기능이 작동하지 않습니다. {{general_description}}
은 구문 분석되지 않습니다.
var obj = {
brand: "Oneida",
general_description: "Plate",
material: "China",
color: "Bone White",
product_width: "5\""
};
const templatePropRe = /{{(\w*)}}/g;
const parse = (template) => {
while ((result = templatePropRe.exec(template)) !== null) {
let match = result[0],
key = result[1];
template = template.replace(match, obj[key]);
}
return template;
}
console.log(parse('This {{color}}, {{material}} {{general_description}} supplied by {{brand}} has a width of {{product_width}}.'));
templatePropRe
)에 먼저 저장해야합니다. 표현식은 while 루프 조건에있을 수 없거나 무한정 반복됩니다. 그러나, 내가 그렇게하면 내 문제가 해결됩니다.
here ... 아무 것도 부러지지 말아라.
String.prototype.match을 사용하여 함수를 다시 작성했지만 예상대로 작동하지만 캡처에 액세스 할 수 없으므로 먼저 stripBrackets
을 사용하여 대괄호를 제거해야합니다. 작업 예제는 match
here을 사용하십시오.
내가 알고 싶은 것은 왜 parse()
RegExp.prototype.exec
을 사용하는 기능이 제대로 작동하지 않는 것입니까?
내 [단일 패스 접근법] (https://stackoverflow.com/a/47990731/3832970)을 확인하십시오. –