[Solved] Write a function firstWord, taking a string and returning the first word in that string. The first word are all characters up to the first space [closed]


There are several problems with your code:

  • go and run is not a valid parameter declaration in the function header. There is confusion here with the parameter and the string value that you expect the function to be called with. In the function header you should list the parameter(s) with variable names. Since the function should be called by passing a string, you could name that variable phrase, or text or something else that is descriptive.

  • let text = "go and run"; should not appear in the function. The function should work for any string, so it should not be hard-coded to “go and run”. The parameter variable will have the actual string that the function is called with.

  • let firstBlank = text.substr(0, 2); is again focusing on one particular string. It actually doesn’t search for a space at all. You — as programmer — tell it that the first word is 2 characters long. Your function then might as well just do return "go". But you should really support any string, and then let the code find out how long the first word is by scanning the string for the first space or end of the string.

  • substr (also in the second code block) is a deprecated function. Use slice instead.

The second code snippet does the job better, but it still goes wrong when the given string only contains one word. In that case, it will return the wrong answer.

Here is a correction to that second function, but using a more descriptive parameter variable:

function firstWord(text) {
  let firstBlank = text.indexOf(' ');
  if (firstBlank == -1) { // There is no space at all -- return the whole string
    return text;
  } 
  return text.slice(0, firstBlank);
}

NB: Using split a shorter solution code is possible.

solved Write a function firstWord, taking a string and returning the first word in that string. The first word are all characters up to the first space [closed]