How do I get the last word of a sentence using jQuery?

How can I get the last word of a sentence using jQuery?

<strong> Examples:

  • get the last word of a sentence

    should return sentence

  • get the last word

    should return word

+3


source to share


3 answers


try it



var lastword = str.split(" ").pop();

      

+6


source


This can be done using JavaScript. Why JQuery?

This will be split

your string in separate components, then it will pop out from the last element of the array and return it.

More details here



alert("get the last word of a sentence".split(" ").pop());
      

Run code


0


source


Try it.

var arr = str.split(' ');

var length = arr.length;

var result = arr[length - 1];

return result;

      

Or you can try this as well.

var lastitem = str.split(" ").pop();

      

0


source







All Articles