What's the shortest way to convert any JavaScript value to a string?

I have a function, say:

setValue: function(myValue) {
  ...
}

      

The caller can pass a string, number, boolean, or object. I need to make sure that the value passed down the line is a string. What's the safest way to do this? I understand that some types (like Date) can be converted to strings, but I'm just looking for something sane out of the box.

I could write a series of operators like:

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

      

But this can be error prone as types can be omitted.

Firefox seems to support things like:

var foo = 10; foo.toString()

      

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

In short, what is the shortest way to perform the conversion while covering each individual type?

-Erik

+1


a source to share


5 answers


var stringValue = String(foo);

      

or even shorter



var stringValue = "" + foo;

      

+9


a source


value += '';

      



+3


a source


If you are using myValue

as a string, Javascript will imply the conversion to a string. If you need to hint at the Javascript engine that you are dealing with a string (like using the + operator), you can safely use toString in IE6 and up.

+2


a source


how to format string context eg. "" + Foo?

0


a source


Another way:

var stringValue = (value).toString();

      

0


a source







All Articles