TMG
TMG

Reputation: 97

jQuery/Javascript - select last word in physical line of paragraph

I'm not sure this is possible but I wondered if there is a way of targeting the last word in a line of text within a paragraph. Note that I'm not looking for the last word in the paragraph but the last word in a line of said paragraph.

I haven't the faintest idea of how to start with this so haven't got an attempt formulated.

Thanks for any help you can offer! Mark

Upvotes: 0

Views: 1322

Answers (4)

Graham Billington
Graham Billington

Reputation: 129

The code below will find the last word of each line (of a p tag), and throw all of them in the console. words[i - 1], or breakWord is the last word of each line. Hopefully, this helps.

var breakWord
var p = $('p');

p.each(function () {
    var current = $(this);
    var text = current.text();

    var words = text.split(' ');

    current.text(words[0]);
    var height = current.height();

    for (var i = 1; i < words.length; i++) {
        current.text(current.text() + ' ' + words[i]);

        if (current.height() > height) {
            height = current.height();
            breakWord = words[i - 1];
            console.log(breakWord);
        }
    }

    console.log(current);
});

This code will split the whole paragraph up into single words, put them in an array (words), and then check for line breaks. When a line break is found, it returns the last word of the line.

Upvotes: 0

Jimmy Ko
Jimmy Ko

Reputation: 877

I found a JS library, jsLineWrapDetector, which can retrieve the lines from the text wrapped by DOM element.

var p = $("p")[0];
var lines = lineWrapDetector.getLines(p);
lines.forEach(function(line) {
  var lastword = line.split(" ").pop();
});

Upvotes: 1

Jax Teller
Jax Teller

Reputation: 1467

You can use this function :

function getLastWord(paragraph, line) {
  return paragraph.split("\n")[line].split(" ").pop();
}

Working Example

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can get the text of p tag, split them on occurrence of space to create the array of word. then target the last element in returned array. Like this:

var wordarray = $('p').text().split(" ");
return wordarray [wordarray.length - 1];

Upvotes: 1

Related Questions