简体   繁体   English

如何获取 JavaScript 中多行文本的单个指定行的最后一个字符?

[英]How to get the last character(s) of a single, specified, line of a multiline text in JavaScript?

Let's say I have a multiline text that fills some <div> element.假设我有一个多行文本来填充一些<div>元素。 Is it possible, and if so – how – to get the last character of a specified line?是否可能,如果可能——如何——获取指定行的最后一个字符?

For example after wrapping inside a div a text becomes:例如,在包裹在一个 div 中后,文本变为:

Lorem ipsum dolor sit amet
consectetur adipiscing elit
Aenean dignissim convallis
lorem ut rhoncus. Duis metus
nulla, aliquet quis pharetra.

I am interested in what is the last character of the line 4 which is the letter "s".我感兴趣的是第 4 行的最后一个字符是字母“s”。 Or I am interested in 3 last characters of the same line, which reads "tus".或者我对同一行的最后 3 个字符感兴趣,上面写着“tus”。

But how could I find this in JS?但是我怎么能在 JS 中找到它呢?

What is more – how could I style those returned letters?更重要的是——我该如何设计那些被退回的信件的样式?

EDIT编辑

No, I can not put that into an array.不,我不能把它放到一个数组中。 The div is of unknown size (responsive) and thus I have no a priori idea where the line breaks appear. div 的大小未知(响应),因此我不知道换行符出现在哪里。

Simply you can put these lines in an array and then loop through the lines and get required number of characters.只需将这些行放在一个数组中,然后循环遍历这些行并获得所需的字符数。

Here I am getting line-4's last 3 characters where variable line and numberOfChars indicate line number and required number of characters from last respectively.在这里,我得到第 4 行的最后 3 个字符,其中变量 line 和 numberOfChars 分别表示行号和最后所需的字符数。

 let array = [ "Lorem ipsum dolor sit amet", "consectetur adipiscing elit", "Aenean dignissim convallis", "lorem ut rhoncus. Duis metus", "nulla, aliquet quis pharetra." ] let line = 4; let numberOfChars = 3; array.forEach((item, index) => { if (index+1 === line) { console.log(item.slice(-numberOfChars)); } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM