Skip to the code
cf.
+25 XP

#628 Tokenize a Message Template

medium

A notification service stores messages as templates like Hi {{ name }}, you have {{count}} new messages. Before filling them in, it splits each template into tokens.

Write tokenizeTemplate(template) that returns a list of tokens in order. Plain text becomes ["text", content]. Each {{ ... }} becomes ["var", name], where name is the text between the braces with surrounding spaces trimmed.

If a {{ has no matching }} after it, everything from the last token's end to the end of the template is plain text. Never output empty text tokens.

Example 1

Input: template = "Hi {{ name }}, you have {{count}} new messages"
Output: [["text","Hi "],["var","name"],["text",", you have "],["var","count"],["text"," new messages"]]

Two variables split the text into three pieces.

Example 2

Input: template = "{{a}}{{b}}"
Output: [["var","a"],["var","b"]]

No text between or around the variables, so no text tokens.

Constraints

  • 0 <= template.length <= 10^4
  • Variable names never contain { or }.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).