여러 <p>
태그 가 포함 된 html 문자열이 있습니다 . 각 <p>
태그에는 단어와 그 정의가 있습니다.
let data = "<p><strong>Word 1:</strong> Definition of word 1</p><p><strong>Word 2:</strong> Definition of word 2</p>"
내 목표는이 html 문자열을 아래와 같은 객체 배열로 변환하는 것입니다.
[
{"word": "Word 1", "definition": "Definition of word 1"},
{"word": "Word 2", "definition": "Definition of word 2"}
]
다음과 같이하고 있습니다.
var parser = new DOMParser();
var parsedHtml = parser.parseFromString(data, "text/html");
let pTags = parsedHtml.getElementsByTagName("p");
let vocab = []
pTags.forEach(function(item){
// This is where I need help to split and convert item into object
vocab.push(item.innerHTML)
});
위의 코드에서 주석을 볼 수 있듯이 이것이 제가 갇혀있는 부분입니다. 도움을 주시면 감사하겠습니다.
textContent
요소에서 텍스트를 가져 오는 데 사용 합니다. 단어는 strong
자식 요소에 있고 정의는 나머지 텍스트입니다.
var parser = new DomParser();
var parsedHtml = parser.parseFromString(data, "text/html");
let pTags = parsedHtml.getElementsByTagName("p");
let vocab = []
pTags.forEach(function(item){
let word = item.getElementsByTagName("strong")[0].textContent.trim();
let allText = item.textContent;
let definition = allText.replace(word, "").trim();
vocab.push({word: word, definition: definition})
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다