Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe way to get a string representation of any JavaScript value or object

Tags:

javascript

I want to get a string represention of any object or value in JavaScript. I did a couple of experiments.

> var a = document.createTextNode('foo'); a
  "foo"
> var a = document.createTextNode('foo'); a.toString()
  "[object Text]"
> var a = 1; a.toString()
  "1"
> (1).toString()
  "1"
> 1.toString()
  SyntaxError: Unexpected token ILLEGAL

I have the following questions:

  1. Why does 1.toString() fail?
  2. Will the following function return me a string representation of every possible JavaScript object, value or literal? Function: function str(a) {return a.toString()}
  3. Is there any other alternative to the function str I have written in the previous point?
like image 907
Lone Learner Avatar asked Sep 22 '13 09:09

Lone Learner


People also ask

How do you get a string from an object JavaScript?

Stringify a JavaScript Object Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is toString () in JavaScript?

The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.


2 Answers

1). Why does 1.toString() fail?

The JavaScript parser only uses a 1 character lookahead and can't determine if that's 1.0 or 1.toString(). You can use 1..toString() to get around that.

2). Will the following function return me a string representation of every possible JavaScript object, value or literal? Function: function str(a) {return a.toString()}

Any literal will be converted to a temporary object in order to have its toString() called. If the object has its own toString() defined, it will be called. Otherwise, it will use Object.prototype.toString() (having gone up the prototype chain) for almost all cases (the other case is an object with a null prototype).

3). Is there any other alternative to the function str I have written in the previous point?

Yes. You can invoke the toString() implicitly by concatenating an empty string, e.g. 1 + "". You can also use the String constructor, e.g. String(value) (thanks T.J. Crowder). The advantages of these other ones is no exception will be thrown if you attempt to call toString() on null or undefined.

However, these tricks will convert null and undefined to their string equivalents (almost never what you want). One dirty trick is to put the value in a literal array, e.g. [value] and then call toString() on it. This will actually invoke join(","), but seeing as it only has one member, the comma will never become part of the string.

The real power of doing this is that null and undefined will just become an empty string. If that's OK for your program, then it can be useful. Keep in mind to comment this solution as it's not immediately obvious what this code is doing. Alternatively, check value == null which will detect null and undefined and handle it appropriately.

However, if you're wanting a string in order to classify a value, you can get the type's [[Class]] like so...

var getInternalClass = function(value) {
    return Object.prototype.toString.call(value).slice(8, -1); 
};

This will invoke the Object's toString() and set the ThisBinding to the value provided as the argument. This is the only way to expose an object's internal [[Class]]. The advantage of this (over typeof, for example) is that primitives and objects will always return the same value (with the primitives being converted to temporary objects, boxed by the call() context in non-strict mode).

like image 84
alex Avatar answered Sep 30 '22 10:09

alex


for 1.toString(), you need to do:

1 .toString() //add space before dot (.) to avoid taking it as decimal

shortest way (alternative to function str ) to convert to string is:

var str = str + '';
like image 33
Sudhir Bastakoti Avatar answered Sep 30 '22 10:09

Sudhir Bastakoti