Search code examples
javascriptstringsubstring

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)


Solution

  • 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];
    
    }