Tuesday, May 4, 2021

Javascript Practice 25: JS Hero - String: substr()

 
Question: 

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.

Example: firstWord('see and stop') should return 'see'.





Answer: 

function firstWord (string) {

let space = string.indexOf(" "); 

return string.substr(0, space);

}; 

> firstWord is a function that returns the first word in a string
> the first word basically are all the characters up to the first space - " "
> the substr() method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards
> syntax =    substr (start) or substr (start, length)
start = index position of the first character to include in the returned substring
length = optional, the number of characters to extract
> we start of with declaring a variable 'space' and initialize it with a value 
> we derive the value by finding the index position of the first space in the string parameter using the indexOf() method
> since we need the first word in the string we then use the substr() method 
> here we instruct the function to start searching the string from the first index position (0) and instead of providing the length of the first word, we provide the variable 'space' (0, space), which is the index position of the first space in the string
> instead of providing the length of the first word to be extracted in numbers, we simply provide the index position of the first space (which is a number) enabling the function firstWord to stop searching for characters of the first word once it reaches the index position of the first space
> we then return string.substr(0, space) 

No comments:

Post a Comment