Question:
Write a function firstChar, which returns the first character that is not a space when a string is passed.
Example: firstChar(' Rosa Parks ') should return 'R'.
Example: firstChar(' Rosa Parks ') should return 'R'.
Answer:
function firstChar (input) {
let x = input.trim();
return x.charAt(0);
};
let x = input.trim();
return x.charAt(0);
};
> function expression
> function name is firstChar
> parameter is input
> declared a variable x and initialized it with a value
> value is a trimmed version of the input parameter
> used the trim() method to remove whitespaces from both the ends of a string (in this case the input parameter)
> when the function firstChar is called, using an argument that has empty spaces on both ends, it will return the first character after trimming the empty spaces
> the first character is accessed by using the charAt(0) method.
No comments:
Post a Comment