ebruchez
ebruchez

Reputation: 7857

What is the shortest way of converting any JavaScript value to a string?

I have a function, say:

setValue: function(myValue) {
  ...
}

The caller might pass a string, number, boolean, or object. I need to ensure that the value passed further down the line is a string. What is the safest way of doing this? I realize there are many ways some types (e.g. Date) could be converted to strings, but I am just looking for something reasonable out of the box.

I could write a series of typeof statements:

if (typeof myValue == "boolean") {}
else if () {}
...

But that can be error-prone as types can be missed.

Firefox seems to support writing things like:

var foo = 10; foo.toString()

But is this going to work with all web browsers? I need to support IE 6 and up.

In short, what is the shortest way of doing the conversion while covering every single type?

-Erik

Upvotes: 1

Views: 541

Answers (5)

Helgi
Helgi

Reputation: 1577

Yet another way is this:

var stringValue = (value).toString();

Upvotes: 0

patjak
patjak

Reputation: 41

If you use myValue as a string, Javascript will implicity convert it to a string. If you need to hint to the Javascript engine that you're dealing with a string (for example, to use the + operator), you can safely use toString in IE6 and up.

Upvotes: 2

Andrey
Andrey

Reputation: 4356

what about forcing string context, e.g. ""+foo?

Upvotes: 0

Fabien Ménager
Fabien Ménager

Reputation: 140195

value += '';

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039268

var stringValue = String(foo);

or even shorter

var stringValue = "" + foo;

Upvotes: 9

Related Questions