Split()
function in JavaScript is super cool. It looks into a given string and split it into an array.
const array = "Jan\n Feb\n Mar".split(/\n/)
// ["Jan", " Feb", " Mar"]
So, if we are curious about knowing how many lines in a given string:
const lines = "Jan\n Feb\n Mar".split(/\n/).length
// 3
Let's put our code into one function so we can develop it easily:
/**
* split string in each line and put it into array.
*/
function splitToLines(lines) {
const linesArray = lines.split(/\n/);
return linesArray;
}
const str = "Hello World\n How are you doing";
const strArr = splitToLines(str) // [ 'Hello World', ' How are you doing' ]
const strLength = strArr.length // 2
We may dive more into each line individually by counting words:
/**
* counts words in an array of lines.
*/
function countWords(linesArr) {
let words = 0;
// go into each line individually.
linesArr.forEach(line => {
// line1: Hello World
// line2: How are you doing
// let's trim the line to avoid spaces in the beginning.
// split each line by spaces so we can count words in each line.
const wordsArr = line.trim().split(/\s/);
// line1-arr: ["Hello", "World"];
// line2-arr: [ "How", "are", "you", "doing" ]
words += wordsArr.length;
// for line1: words equal to 2
// for line1: words equal to 4
});
return words;
}
const str = "Hello World\n How are you doing";
const linesArr = splitToLines(str) // [ 'Hello World', ' How are you doing' ]
const wordsNum = countWords(linesArr) // 6
const linesNum = linesArr.length // 2
It's fun, exactly like solving a puzzle. You start with the first piece and suddenly you nearly there.
Think about it, if you have lines and words number, you can easily count characters in each word and calculate spaces.
This is exactly how I built a function called textics. It counts lines, words, chars and spaces for a given string using split()
function and that all can be done with couple lines of code.
Do you like it? Please leave a ⭐️. I appreciate any feedback or PRs 👋👋👋
I think all these three are similar,
. split('\n')
,. split(/\n/)
and. split(/\n/g)
.Do you know that you can
. split(/\.(.+)$/)
?