【问题标题】:How can I get the number of characters in a line in a template literal?如何获取模板文字中一行中的字符数?
【发布时间】:2022-11-14 08:39:27
【问题描述】:

我有一个多行模板文字。我想根据行中的行号和字符索引进行拼接。为此,我需要给定行中的字符数。我怎样才能得到这个号码?

至于我尝试过的,好吧,我几乎只是将随机数放入slice() 以查看它切片了多少。

谢谢。

【问题讨论】:

  • how-to-ask。你试过什么?
  • 只是分成几行,拿你想要的,按索引切片?
  • 谢谢@Bergi!对不起,我只是在字符串方面有一些东西要学^^

标签: javascript string slice template-literals


【解决方案1】:

split() 获取每一行。 filter() 上的 True 值以删除空索引。

现在您可以在所需索引上使用 .length 来获取该行的长度:

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

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

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

【讨论】:

    【解决方案2】:
    let text =
      `The quick
    brown fox
    jumps over
    the lazy dog`;
    let res = text.split('
    ');
    res.forEach((element, index)=>{
      console.log(`Line no:${index+1}   ${element}     length: ${element.length}`);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多