简体   繁体   中英

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. 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:

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". Or I am interested in 3 last characters of the same line, which reads "tus".

But how could I find this in 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.

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.

 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)); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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