Checking for an Existing, Nonempty String Javascript

Last Updated On Saturday 2nd Oct 2021

Make sure that your variable is a string.

	if (typeof unknownVar === 'string') {
  // unknownVar is a string
}
	

Make Sure that you have a non-empty string (not the zero-length string(“”)

	if (typeof unknownVar === 'string' && unknownVar.length > 0) {
  // string with characters or whitespace
}
	

If You want to reject strings that are made up of whitespace only, in which case you can use the String.trim() method.

	if (typeof unknownVar === 'string' && unknownVar.trim().length > 0) {
  // String that is not empty or all whitespace
}
	

If we already know unknownVar is a string

	if (unknownVariable.length > 0)
	
	const unknownVariable = new String('test');
	

The type of operator will return an object instead of a String because the String primitive is wrapped in a String object.

	if (typeof unknownVariable === 'string' ||
    String.prototype.isPrototypeOf(unknownVariable)) {
  // String wrapped in an object.
}
	

You have a string primitive or an object that has the same prototype as String. It returns the type name of the variable as a lowercase string.

	undefined

boolean

number

bigint

string

symbol

function

object
	
	if (unknownVar) {
/* unknownVar has been declared, is not null,is not the empty string ''*/
}
	

It simply verifies that your value can be treated as a string.

This works because null values, undefined values, and empty strings (”) are all falsy in JavaScript. If you evaluate any of them in a conditional expression, they are treated as false.