Get the Last Word of a String in JavaScript-Code Examples

Radu TM

Get the Last Word of a String in JavaScript

JavaScript by Radu TM June 17, 2022

//This function takes in a string and returns the last word
function getLastWord(str) {
  //We first need to check if the string is empty
  if (str === "") {
    return str;
  }
  //Split the string into an array of words
  let words = str.split(" ");
  //Return the last word in the array
  return words[words.length - 1];
}

0

21.291

Get the Last Word of a String in JavaScript

JavaScript by Radu TM June 17, 2022

// this function takes a string as an input and returns the last word of the string

function lastWord(str) {
  // we first need to split the string into an array of words
  var words = str.split(" ");

  // then we return the last word in the array
  return words[words.length - 1];
}

0

21.291

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories