Detecting a string

suggest change

To detect whether a parameter is a primitive string, use typeof:

const aString = "my string";
const anInt = 5;
const anObj = {};
typeof aString === "string";   // true
typeof anInt === "string";     // false
typeof anObj === "string";     // false

A String object from new String("somestr") has typeof "object", so the test above misses it. instanceof String catches that object in the same realm. It misses a String object from another window or iframe.

const aStringObj = new String("my string");
aStringObj instanceof String;    // true

To cover both instances, we can write a simple helper function:

const isString = function(value) {
    return typeof value === "string" || value instanceof String;
};

const aString = "Primitive String";
const aStringObj = new String("String Object");
isString(aString); // true
isString(aStringObj); // true
isString({}); // false
isString(5); // false

Object.prototype.toString reports both forms as "[object String]", including a String object from another realm. It also distinguishes other built-in types, so it fits a switch.

const pString = "Primitive String";
const oString = new String("Object Form of String");
Object.prototype.toString.call(pString);//"[object String]"
Object.prototype.toString.call(oString);//"[object String]"

A more robust solution is to not detect a string at all, rather only check for what functionality is required. For example:

const aString = "Primitive String";
// Generic check for a substring method
if (aString.substring) {

}
// Explicit check for the String substring prototype method
if (aString.substring === String.prototype.substring) {
    aString.substring(0);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents