JavaScript: Check whether an 'input' is a string or not
JavaScript String: Exercise-1 with Solution
Write a JavaScript function to check whether an 'input' is a string or not.
Test Data:
console.log(is_string('w3resource'));
true
console.log(is_string([1, 2, 4, 0]));
false
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named is_string that takes an input parameter
is_string = function(input) {
// Check if the type of input is a string by examining its internal [[Class]] property
if (Object.prototype.toString.call(input) === '[object String]')
// Return true if the input is a string
return true;
else
// Return false if the input is not a string
return false;
};
// Output the result of calling the is_string function with a string argument
console.log(is_string('w3resource'));
// Output the result of calling the is_string function with an array argument
console.log(is_string([1, 2, 4, 0]));
Output:
true false
Explanation:
In the exercise above,
- The "is_string()" function is defined, taking one parameter as input.
- Inside the function, it checks the type of 'input' by using Object.prototype.toString.call('input').
- If the result of this check matches the string '[object String]', it returns 'true', indicating that the input is a string.
- Otherwise, it returns 'false', indicating that the input is not a string.
- The function definition ends.
- Two examples are provided to demonstrate the "is_string()" function with different types of input: a string ('w3resource') and an array ([1, 2, 4, 0]).
- The results of calling "is_string()" with these inputs are printed to the console using console.log.
Flowchart:
Live Demo:
See the Pen JavaScript Print an integer with commas as thousands separators - string-ex-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Javascript String Exercises.
Next: Write a JavaScript function to check whether a string is blank or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-string-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics