-1

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.

mikwee
  • 133
  • 2
  • 14

3 Answers3

1

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`);
}
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • What exactly does `v => v` mean? I assume it is a lambda function... – mikwee Nov 11 '22 at 15:15
  • 1
    It's a short way of [removing all empty strings from an array](https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript) – 0stone0 Nov 11 '22 at 15:16
1
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}`);
})
0

At the end, I used split(), then sliced the element in the array corresponding to the line I want. Example:

var text = `As the trees grow
I'm starting to know
That I love you`;

var splitText = text.split("\n");
var slice = splitText[1].slice(4, 15);
console.log(slice); // starting to
mikwee
  • 133
  • 2
  • 14