Currently I have this string:
"Hello, I'm <%first%> <%last%>, and I <3 being a <%occupation%>. I am > blah";
How do I separate it into a an array of object that looks like this:
[
{ type: 'string', value: 'Hello, I'm ' },
{ type: 'token', value: 'first' },
{ type: 'string', value: ' ' },
{ type: 'token', value: 'last' },
{ type: 'string', value: ', and I <3 being a ' },
{ type: 'token', value: 'occupation' },
{type: 'string', value: 'I am > blah'}
]
The pattern of the string is that if we find a word that looks like this: <%word%>, then we put that into the array as an object with type token. Otherwise we put it in as a type string. My question is how do we implement it in code.
I'm having difficulty with forming the phrase which is going to be the value for the key value. Below is a code that I tried to implement, but it is faulty.
My idea is to have a word variable, which is empty, and as it goes through the string it concats the words to form the phases. Once it see that it's in between <% and %>, it will be given a type token and push into the arrStr array.
However 2 issues: 1) It seems that with this code, each iteration of the string from "H" to "He" to "Hel" to "Hell" to "Hello" is being generated. 2) It seems like it never touches token. 3) The first "h" in "hello" is somehow omitted.
How do I do this without using regex?