Oh no!

Find the magic from a String to a List

This is a so simple tips I never remember when I need it.

So I think it's worst saving it here for, at least for my future self.

Note for future self: You probably remember this since your past self wrote it here.

the concept

Sometimes you might come across a situation where you need to create a list of items (ul > li) using a unique string.

— A what?! Yes, a uniiiiiique String.

This string contains all the list items concatenated together separated by "something". It might seem odd, but that's just the way it's designed.

While some may argue that it's not the best design, you still have to work with it and find a way to make it work for let you jump on the next task.

the string

const textString = "this is the first string\n Here, the second string\n Finally, this is the third string"

the "something"

Did you notice the little something in the String? This little weirdo is an character escape (\n for newline: see extra note section for more) and it will be useful for us to "split" the String into multiple list items.

the trick (in vanilla js)

const list = document.createElement("ul");

textString.split("\n").forEach((item) => {
  const li = document.createElement("li");
  li.textContent = item;
  list.appendChild(li);
});

the trick (in Vue.js)

<ul>
  <li v-for="(item, index) in textString.split('\n')" :key="index">
    {{ item }}
  </li>
</ul>

✨ extra note

Are you wondering what exactly is the \n is?

The \n is the newline character escape. They are useful to manipulate the way the text is displayed without including characters that would break the code.

Here the list of few character escape:

👨‍💻 In our use case, the escape character will not break the code because it is in a string. But using it this way, it's so easy to find.

Thanks for reading this, let's back to code now

If you want to discuss this simple tips, feel free to reach out to me (the link opens a new tab). I'd be happy to hear from you.

🧠