본문 바로가기

LeetCode

CodeTestcaseTest ResultTest Result1410. HTML Entity Parser / TypeScript

HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.

The special characters and their entities for HTML are:

  • Quotation Mark: the entity is " and symbol character is ".
  • Single Quote Mark: the entity is ' and symbol character is '.
  • Ampersand: the entity is & and symbol character is &.
  • Greater Than Sign: the entity is > and symbol character is >.
  • Less Than Sign: the entity is &lt; and symbol character is <.
  • Slash: the entity is &frasl; and symbol character is /.

Given the input text string to the HTML parser, you have to implement the entity parser.

Return the text after replacing the entities by the special characters.

 

Example 1:

Input: text = "&amp; is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
Explanation: The parser will replace the &amp; entity by &

Example 2:

Input: text = "and I quote: &quot;...&quot;"
Output: "and I quote: \"...\""

 

 

출처: https://leetcode.com/problems/html-entity-parser/description/

 

 

풀이

 

function entityParser(text: string): string {
    const parser = {
        '&quot;': '"',
        '&apos;': "'",
        '&amp;': '&',
        '&gt;': '>',
        '&lt;': '<',
        '&frasl;': '/',
    } 

    const entities: string[] = Object.keys(parser);
    
    let newText = text;

    entities.forEach(entity => {

        if(text.search(entity) !== -1) {
            newText = newText.replaceAll(entity, parser[entity])
        }

    });

    return newText
};

 

주어진 문자열에서 HTML 엔터티들을 찾아서 해당 엔터티를 실제 문자로 변환한 후 새로운 문자열로 반환

 

1. entities.forEach(entity => { ... })

  • entities는 parser 객체에서 가져온 HTML 엔터티 목록.
  • 예를 들어, ['&quot;', '&apos;', '&amp;', '&gt;', '&lt;', '&frasl;']와 같은 배열.
  • forEach는 배열의 각 요소(여기서는 entity)에 대해 반복문을 실행.

2. if(text.search(entity) !== -1)

  • text.search(entity)는 입력된 문자열 text에서 현재 엔터티(entity)가 존재하는지 찾는 함수.
  • search 함수는 찾는 문자열의 시작 위치를 반환. 만약 찾는 문자열이 없다면 -1을 반환.
  • 따라서 if(text.search(entity) !== -1)은 "입력 문자열 text에 현재 엔터티가 존재하는가?"를 확인하는 조건문.
  • 만약 entity가 text 내에 있다면 그 위치를 반환하므로, !== -1 조건은 true.

3. newText = newText.replaceAll(entity, parser[entity])

  • 이 부분은 newText라는 문자열에서 entity를 찾아서 대응되는 실제 문자(parser[entity])로 전부 교체.
  • replaceAll(entity, parser[entity])은 entity라는 HTML 엔터티를 parser[entity]에 정의된 실제 문자로 바꾸는 함수.
  • 예를 들어, entity가 &quot;이라면, parser[entity]는 " . 따라서 newText.replaceAll('&quot;', '"')가 됨.
  • 이 과정이 forEach 반복문에서 모든 엔터티에 대해 수행