How to convert anything to a String safely in JavaScript

erikvold picture erikvold · Nov 30, 2010 · Viewed 10.9k times · Source

If I have:

var test = {toString: function(){alert("evil code"); return "test";}};

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

Answer

Ivo Wetzel picture Ivo Wetzel · Nov 30, 2010

Your (toString: function(){alert("evil code"); return "test";}) doesn't even get parsed here, it throws a syntax error. I think you wanted to use {} instead of ().

Normally you could use an empty string and the plus operator to perform a cast:

""+test;
""+2; // "2"
""+4.5 // "4.5"
""+[1, 2, 3] // "1,2,3"
""+{} // '[object Object]'

But here, there's no real way to convert the object safely.

You can use delete test.toString to get rid of the overridden method, after that it will fall back to the normal toString method which returns '[object Object]'. You can also convert the toString method itself into a string via test.toString.toString().

"function () { alert("evil code"); return "test"; }"

It's up to you what you exactly want to do here.