How can I check if a var is a string in JavaScript?
I've tried this and it doesn't work...
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
You were close:
if (typeof a_string === 'string') {
// this is a string
}
On a related note: the above check won't work if a string is created with new String('hello') as the type will be Object instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.
The typeof operator isn't an infix (so the LHS of your example doesn't make sense).
You need to use it like so...
if (typeof a_string == 'string') {
// This is a string.
}
Remember, typeof is an operator, not a function. Despite this, you will see typeof(var) being used a lot in the wild. This makes as much sense as var a = 4 + (1).
Also, you may as well use == (equality comparison operator) since both operands are Strings (typeof always returns a String), JavaScript is defined to perform the same steps had I used === (strict comparison operator).
As Box9 mentions, this won't detect a instantiated String object.
You can detect for that with....
var isString = str instanceof String;
jsFiddle.
...or...
var isString = str.constructor == String;
jsFiddle.
But this won't work in a multi window environment (think iframes).
You can get around this with...
var isString = Object.prototype.toString.call(str) == '[object String]';
jsFiddle.
But again, (as Box9 mentions), you are better off just using the literal String format, e.g. var str = 'I am a string';.
Further Reading.
Combining the previous answers provides these solutions:
if (typeof str == 'string' || str instanceof String)
or
Object.prototype.toString.call(str) == '[object String]'
Following expression returns true:
'qwe'.constructor === String
Following expression returns true:
typeof 'qwe' === 'string'
Following expression returns false (sic!):
typeof new String('qwe') === 'string'
Following expression returns true:
typeof new String('qwe').valueOf() === 'string'
Best and right way (imho):
if (someVariable.constructor === String) {
...
}
Now days I believe it's preferred to use a function form of typeof() so...
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
check for null or undefined in all cases a_string
if (a_string && typeof a_string === 'string') {
// this is a string and it is not null or undefined.
}
My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.
function isString(x) {
return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}
See: http://jsfiddle.net/x75uy0o6/
I'd like to know if this method has flaws, but it has served me well for years.
Related
I have a an object jsonRes[0] containing values which need to be removed based on a condition. The following works to remove null, missing values and those equal to zero in the stringified object:
function replacer(key, value) {
// Filtering out properties
if (value === null || value === 0 || value === "") {
return undefined;
}
return value;
}
JSON.stringify(jsonRes[0], replacer, "\t")
However, when I add a condition using the the includes method, I receive an error:
function replacer(key, value) {
// Filtering out properties
if (value === null || value === 0 || value === "" || value.includes("$")) {
return undefined;
}
return value;
}
Uncaught TypeError: value.includes is not a function
Why is this the case and is there a workaround?
You can use String.indexOf() instead of String.includes, As it is available in ES6 and not supported in IE at all.
typeof value == "string" && value.indexOf('$') > -1
Also note if value is not string type it will still raise an error boolean, Number doesn't the the method. You can use typeof to validate whether value is a string.
The .includes() API is part of the String and Array data type.
So what the error is trying to tell you is that the value for variable value, e.g. an integer or object, does not have the property .includes.
You could do checks like
typeof a_string === 'string'
an_array instanceof Array
before the .includes() api to prevent this.
Obviously this will make your if statement rather ugly due to the number of checks you have.
Based on the way your code is written I suspect you are more interested in checking "String" than array. So becareful of arrays. Your code may not work properly if it is array.
Anyway here is a refractored version of your code.
function replacer(key, value) {
// Filtering out properties
if (!value || typeof value === "string" && value.includes("$")) {
return undefined;
}
return value;
}
console.log("NULL returns:" + replacer('test', null));
console.log("$Test returns:" + replacer('test', '$test'));
console.log("Blah returns:" + replacer('test', 'Blah'));
Just one more possibility: Maybe your value is not a string type object.
(typeof(value) == "string" && value.includes("$"))
I solved this error, which I was getting when applying "includes" to a "window.location" value, by appending ".toString();"
var requestUrl = window.location.toString();
if (requestUrl.includes(urlBase + "#")) {
...
I actually am not sure what type of the variable named value is, but anyway, Array.prototype.includes and String.prototype.includes are only available in ES6. You need to use babel-polyfill or any other bundling modules like rollup.js, webpack with babel or something like that to use includes function.
What I have so far.
const isNotNullObject = function (x) {
return (typeof x === "object" && x !== null);
};
It works fine for arrays and objects. But for String objects too !
isNotNullObject(String(5))
false
isNotNullObject(new String(5))
true
What I want is false for any type of string. Note that I don't have control of the calling code. I can't remove new myself. I need a solution that does not create a new String just to check for equality if possible for performance reasons.
Use instance of
return (typeof x === "object" && !(x instanceof String) && x !== null)
const isNotNullObject = function(x) {
return (typeof x === "object" && !(x instanceof String) && x !== null);
};
console.log(
isNotNullObject(String(5)),
isNotNullObject(new String(5))
)
There are many ways to check type of Object/String/Array.
using type of X operator using
Object.prototype.toString.apply(X)
//Its performance is worst
Object.getPrototypeOf(X)
X.constructor.
Where X can be Object/Array/String/Number or Anything. For performance Comparison Please see below image
I want to set a Value in a javascript object only when it is not set. My (test) function looks like:
var test = function(){
this.value = {};
this.setValue = function(seperator, newValue){
console.log((this.value[seperator] === "undefined")); //Why both times false?
if(typeof(this.value[seperator] === "undefined")){
this.value[seperator] = newValue;
}else{
//noop
}
console.log(this.value[seperator]);
}
}
var blubb = new test();
blubb .setValue("foo","bar");
blubb .setValue("foo","notme");
in the js console it returns
false
bar
false
notme
Can someone tell me why both time my test of "undefined" told me that is not defined?
thanks in advance
Because undefined in JS is not a string, it's a property of global object and you comparing by type using ===.
=== will compare not only values but their types too:
1 === "1" // false
1 == "1" // true
Try this:
console.log(( typeof this.value[seperator] === "undefined"));
typeof operator transforms variable type to string and only then you can check if your variable is equal to string undefined.
In your second piece of code:
if(typeof(this.value[seperator] === "undefined")){
you use typeof operator outside of the variable so your code first checks if this.value[seperator] === "undefined" then it returns false to you and then you check by "typeof false", it will return boolean for you.
In final step your code converts to:
if( "boolean" ){
And this is always true as string is not empty.
Short answer:
"undefined" !== undefined
Check for undefined instead.
> var foo = { foo: 'foo' };
> foo['bar']
undefined
> typeof(foo['bar'])
"undefined"
Also note that typeof(this.value[seperator] === "undefined") means typeof(boolean) as it'd first evaluate your expression (this.value[seperator] === "undefined") and then get the type of that.
You probably meant typeof(this.value[seperator]) === "undefined".
Your brackets are in the wrong place in this line:
if(typeof(this.value[seperator] === "undefined")){
You're doing the typeof of (this.value[seperator] === "undefined") - that's a boolean condition (will return true or false) so I'd expect typeof to give you "boolean". Then your if statements condition is the string "boolean" which, since it's not zero length, is considered true in JavaScript.
What you wanted is:
if((typeof this.value[seperator]) === "undefined") {
How can I check if variable in java script is type of a particular object? What will be the result of this
var myvalue = "200"+50+44;
1) The typeof operator returns a string indicating the type of the unevaluated operand.
2) The result will be 2005044
I think you're trying like this
parseInt("200", 10)+50+44 // returns 294
Check parseInt(string, radix) for more information.
The type can be checked with the typeof operator.
typeof myvalue === "number"
The possible types are "number", "string", "object", "undefined". This has a few problems though.
typeof someArray === "object"
typeof null === "object"
The better way is compare constructors.
someArray.constructor === Array
someNumber.constructor === Number
You do however need to check if it's null or undefined, because neither have a constructor property.
someThing != null && someThing.constructor === SomeConstructor
Let's suppose we have a variable that could be a function, object or array.
I want to find the most efficient way to determinate it.
I think the following way is not optimized because if I know that isFunction = true I don't want to calculate the other variables (isArray, isObject);
What is the order to calculate them, which optimize the resources,
by using the ternary operation?
var isFunction,
isArray,
isObject;
var obj = function () {};
isFunction = (typeof obj === "function") ? true : false;
isArray = (obj.length > 0) ? true : false;
isObject = (typeof obj === "object") ? true : false;
console.log(isFunction , isArray , isObject ); // true, false, false (the good way)
console.log(isFunction , isArray , isObject ); // true, undefined, undefined
I'd say this is as "efficient" as I can make it. It's short, but readable, and should do the job correctly. It will be performant in modern browsers that have a native implementation of some, and the nature of some is such that it only executes the callback until one of the items in the array meets the condition.
Just make sure you add in Array.prototype.some for older browsers.
function isOneOf(obj, types) {
var type;
type = Object.prototype.toString.call(obj);
return types.split(' ').some(function (t) {
return type.indexOf(t) > -1;
});
}
isOneOf({}, 'Array Object Function');
This should work for Array, Date, Error, Function, Null, Number, Object, String, and Undefined. I haven't done thorough cross-browser testing with all those types, so make sure to do some good unit-testing before taking my word for it.
The following functions are ways how the dojo toolkit tests for arrays, functions, etc
isString = function(it){
return (typeof it == "string" || it instanceof String); // Boolean
},
isArray = function(it){
return it && (it instanceof Array || typeof it == "array"); // Boolean
},
isFunction = function(it){
return opts.call(it) === "[object Function]";
},
isObject = function(it){
return it !== undefined &&
(it === null || typeof it == "object" || lang.isArray(it) || lang.isFunction(it)); // Boolean
},
isArrayLike = function(it){
return it && it !== undefined && // Boolean
// keep out built-in constructors (Number, String, ...) which have length
// properties
!lang.isString(it) && !lang.isFunction(it) &&
!(it.tagName && it.tagName.toLowerCase() == 'form') &&
(lang.isArray(it) || isFinite(it.length));
},
I don't see the point of trying to optimize this kind of code. If you really cared about optimizations, you should probably use simpler non-overloaded functions where these checks are not necessary.