How can I determine whether a variable is a string or something else in JavaScript?
35 Answers
I needed to check if the variable is a string and wanted to do it "quick and dirty". Here is my approach. Since only string have replaceAll method this is enough eficient.
const isString = (input) => typeof input?.replaceAll === 'function'
// Examples of usage
console.log(isString(true))
// For both of them it will be true
console.log(isString(new String('test')))
console.log(isString('test'))
1 Comment
In old browsers you could reliably test for string objects and primitives with Object.prototype.toString() which would return '[object String]' only on string values. But with the addition of Symbol.toStringTag in ES6, you can no longer rely on Object.prototype.toString() to always tell you the correct object class.
So to avoid potential false positives and negatives I wrote this function which first checks whether Symbol.toStringTag is a property of the tested value. If so, it tests the value with String.prototype.toString() which throws on non-string values. Otherwise it avoids the unnecessary overhead of try/catch with the faster way of testing for strings with Object.prototype.toString().
Works in both modern and old browsers with 100% accuracy:
var isString = function(){
function isntString(value){// isolate try/catch for better performance in old browsers
try{
''.toString.call(value);// throws on non-string values
}
catch(e) {
return true
}
}
var toStringTag = typeof Symbol=='function' && Symbol.toStringTag;
return function isString(value) {
return typeof value=='object' && value? toStringTag && toStringTag in value?
!isntString(value): {}.toString.call(value)=='[object String]': typeof value=='string'
}
}();
isString('');// true
isString(new String);// true
isString({[Symbol.toStringTag]:'String'});// false
Comments
A code to have only string without any numbers
isNaN("A") = true;
parseInt("A") = NaN;
isNaN(NaN) = true;
Than we can use isNaN(parseInt()) to have only the string
let ignoreNumbers = "ad123a4m";
let ign = ignoreNumbers.split("").map((ele) => isNaN(parseInt(ele)) ? ele : "").join("");
console.log(ign);
1 Comment
Below are two simple functions that should be fairly fast and work correctly for all the different types of string instances/variables. One for a scalar value check and the other for a vector of values to check.
const isString = x => !!x?.toUpperCase;
['', 'a', new String, String('a'), String(1)].map(v => isString(v));
// [true, true, true, true, true]
[null, undefined, 0, 1, true, [], ['a'], {}, {a: 'a'}].map(v => isString(v));
// [false, false, false, false, false, false, false, false, false]
const isStringArray = x => x.map(v => !!v?.toUpperCase).reduce((a, b) => a && b, true);
isStringArray([]);
// true
isStringArray(['', 'a', new String, String('a'), String(1)]);
// true
isStringArray(['', 'a', new String, String('a'), String(1), 1]);
// false
isStringArray([undefined]);
// false
isStringArray([null]);
// false
isStringArray([true]);
// false
isStringArray([false]);
// false
isStringArray([0]);
// false
isStringArray([1]);
// false
isStringArray([[]]);
// false
isStringArray([['a']]);
// false
isStringArray([{}]);
// false
isStringArray([{a: 'a'}]);
// false
Comments
I'm not sure if you mean knowing if it's a type string regardless of its contents, or whether it's contents is a number or string, regardless of its type.
So to know if its type is a string, that's already been answered.
But to know based on its contents if its a string or a number, I would use this:
function isNumber(item) {
return (parseInt(item) + '') === item;
}
And for some examples:
isNumber(123); //true
isNumber('123'); //true
isNumber('123a');//false
isNumber(''); //false
1 Comment
/^\d+$/.test('123') to avoid the intricacies of potential parsing issues)