Home > OS >  How can I get the number of characters in a line in a template literal?
How can I get the number of characters in a line in a template literal?

Time:11-11

I have a multi-line template literal. I want to splice it based on line number and character index in the line. For that, I need the number of characters in a given line. How can I get this number?

As for what I have tried, well, I pretty much only put random numbers into slice() to see how much it slices.

Thanks.

CodePudding user response:

let text =
  `The quick
brown fox
jumps over
the lazy dog`;
let res = text.split('\n');
res.forEach((element, index)=>{
  console.log(`Line no:${index 1}   ${element}     length: ${element.length}`);
})

CodePudding user response:

split() on \n to get each line. filter() on True value to remove the empty indexes.

Now you can use .length on the desired index to get the length of that line:

const templateLiteral = `
Hello
FooBar
Something else on this line
123456789
`;

const lines = templateLiteral.split("\n").filter(v => v);

for (let i in lines) {
    console.log(`Line ${ i   1} has: ${lines[i].length} chars`);
}

  • Related