Detecting a string

suggest change

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

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

If you ever have a String object, via new String("somestr"), then the above will not work. In this instance, we can use instanceof:

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

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

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

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

Or we can make use of toString function of Object. This can be useful if we have to check for other types as well say in a switch statement, as this method supports other datatypes as well just like typeof.

var pString = "Primitive String";
var 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:

var 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:


Strings:
* Syntax
* Detecting a string

Table Of Contents
8 Strings
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde