image
1) Using \n to Split string
Previously, we used the \n to split a string. The \n indicated new line. You can simply add it within a string. For example,
<script>
let split_string = () => {
const str = 'Hello, \n I am \n Arun \n Banik';
document.getElementById('dFyn').innerText = str;
}
split_string();
</script>
See the string constant str has values along with \n. If it’s a long string (a sentence or a paragraph), it can be messy. You’ll have to add new line (\n) after every string or value.
Note: I am writing the string in a <div> element on my web page using innerText property. However, if you want to add string using .innerHTML, then replace \n with <br />. And the code should be,
let split_string = () => { const str = 'Hello, <br /> I am <br /> Arun Banik'; // Show multi line using <br />. document.getElementById('dFyn').innerHTML = str; // Using innerHTML property. } split_string();
2) Using .split() and .join() Methods
You can use these methods occasionally, in a different scenario. You can use the .split() method and the .join() method together to split a string into multiple lines. Here again you will have to use the \n (new line). However, not within the strings (like the 1st example above), but only once.
<script> let split_string = () => { const str1 = 'Hello, I am Arun Banik'; const arr = str1.split(' '); document.getElementById('dFyn').innerText = arr.join('\n'); } split_string(); </script>
This is clean. However, I am using two different methods here and it might look a little complicated (but its not). I have used this technique a few times. There’s no need to add \n repeatedly within the string.
And again, if you are using the .innerHTML property, then do this.
document.getElementById('dFyn').innerHTML = arr.join('<br />');
Output is the same.
3) Using ES6 Template Literals
There is new ES6 feature, called the Template Literals. Its a clean and an easy way to split a string into multiple lines.
<script>
let split_string = () => {
const str = `Hello,
I am
Arun
Banik`;
document.getElementById('dFyn').innerText = str;
}
split_string();
</script>
Careful here. The string is not within a single quote, its within a back quote ( ` ). Its with the tilde (~) symbol on the key board.
Remember: The output may be different when using the console.log() method. So, be careful with spaces.
The methods that I have shared are simple and it uses a combination of plain old JavaScript and a new ES6 feature. There’s no need to use a third party tool and a library.
👉 Do you know you can easily remove duplicates in JavaScript array using an ES6 feature? Check out this article.