Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Returning the last word in a string

right to it:

I have a words string which has two words in it, and i need to return the last word. They are seperated by a " ". How do i do this?

function test(words) {  var n = words.indexOf(" "); var res = words.substring(n+1,-1); return res;  } 

I've been told to use indexOf and substring but it's not required. Anyone have an easy way to do this? (with or without indexOf and substring)

like image 748
Andrew P Avatar asked Jan 02 '14 12:01

Andrew P


People also ask

How do you return the last element of a string?

To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.

How do you find the last word in an array?

Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).

How do I get the last 5 characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.


1 Answers

Try this:

you can use words with n word length.

example:

  words = "Hello World";   words = "One Hello World";   words = "Two Hello World";   words = "Three Hello World"; 

All will return same value: "World"

function test(words) {     var n = words.split(" ");     return n[n.length - 1];  } 
like image 92
Jyoti Prakash Avatar answered Sep 22 '22 10:09

Jyoti Prakash