Javascript is_string()
Click here to view the is_string() demo
JavaScript doesn't have a built-in is_string() function like PHP does. However, you can copy and paste this function into your JavaScript source and use it as you would in PHP.
The Function
<script type="text/javascript">
function is_string(input){
return typeof(input)=='string';
}
</script>
Warning! If you use is_string() to validate form input, it will not work! All form inputs are strings, even if the user typed a number.
When validating form input, use this:
<script type="text/javascript">
function form_input_is_string(input){
return typeof(input)=='string' && isNaN(input);
}
</script>
Using is_string
You can use is_string() right in your JavaScript code, just like you would use it in PHP. For example, say we want to find out if the variable name is a string:
<script type="text/javascript">
//is name a string?
if(is_string(name)){
alert("Your name is a string!");
} else {
alert("Your name is not a string...");
}
</script>
Using form_input_is_string()
Use form_input_is_string() when validating form input. For example:
<input type="text" id="testinput" />
<button onclick="alert(form_input_is_string(document.getElementById('testinput').value))">Is it a string?</button>
Or, when pulling input from a form:
<script type="text/javascript">
//get the form input
var name = document.getElementById('name').value;
//check if name is a string
if(form_input_is_string(name)){
alert("Your name is a string!");
}
else{
alert("Your name is not a string...");
}
</script>
Code Explanation
This function is a one-liner. Pretty simple, huh?
The typeof() function accepts any input and will return that input's type. So, if it says that the type of our function input is 'string', that means our input is a string.
Here is a list of some common JavaScript variable types:
- string
- Boolean
- number
- function
- object
- undefined
In the form_input_is_string() function we also use the JavaScript function isNaN(). NaN stands for "Not a Number". So, if the input is not a number, isNaN() returns true.