anon
anon

Reputation:

A better javascript to string function?

Before I go and create this myself, I thought I'd see if anyone knows a library that does this.

I'm looking for a function that will take something in Javascript, be it an array, an associative array, a number, or even a string, and convert it to something that looks like it. For example:

toString([1,2,3]) === '[1, 2, 3]'
toString([[1,2], [2,4], [3,6]]) === '[[1,2], [2,4], [3,6]]'
toString(23) === '23'
toString('hello world') === 'hello world'
toString({'one': 1, 'two': 2, 'three': 3}) === "{'one': 1, 'two': 2, 'three': 3}"

Upvotes: 0

Views: 271

Answers (1)

Andy E
Andy E

Reputation: 344715

As mentioned in the comments (and I'm surprised nobody actually posted it as an answer), JSON.stringify() is the method that you're looking for. It's supported natively in most browsers these days, but you can also implement it in the browsers that don't support it using json2.js.

Working demo: http://jsfiddle.net/AndyE/WXfzJ/

The only exception is function objects, which won't be stringified by JSON. However, Function.prototype.toString will return a re-parseable string representation of the function, although you should be aware that white-space and comments may be stripped depending on the browser:

function moo() {
    alert('cow says moo!');
}

alert(moo.toString());

Upvotes: 4

Related Questions