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

Radu TM

Get the First Word of a String in JavaScript

JavaScript by Radu TM June 17, 2022

// this function takes a string as an input and returns the first word of the string 
// if the input is not a string, the function returns an empty string 
function getFirstWord(str) {
  // if the input is not a string, return an empty string 
  if (typeof str !== 'string') { return ''; }
  // split the input string by spaces and get the first element in the resulting array
  const firstWord = str.split(' ')[0];
  // return the first word 
  return firstWord;
}

0

22.428

Get the First Word of a String in JavaScript

JavaScript by Radu TM June 17, 2022

// this function takes a string as input and returns the first word

function getFirstWord(str) {
  // we use the 'split' method to split the string into an array of words
  // by splitting at the space character
  var words = str.split(' ');
  // we return the first word from the array
  return words[0];
}

0

22.428

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories