to-safe-string
v1.0.1
Published
Converts any JavaScript value into a string, safely
Maintainers
Readme
to-safe-string
Converts any JavaScript value into a string, safely — whether it's undefined, null, objects, functions, symbols, BigInt, circular references, or Errors.
Installation
npm install to-safe-stringUsage
const toSafeString = require('to-safe-string');
// or: import toSafeString from 'to-safe-string';
toSafeString(42); // "42"
toSafeString("hello"); // "hello"
toSafeString(undefined); // "undefined"
toSafeString(null); // "null"
toSafeString([1, 2, 3]); // "[1,2,3]"
toSafeString({ a: 1, b: 2 }); // '{"a":1,"b":2}'
toSafeString(function foo() {}); // "function foo() {}"
toSafeString(Symbol('test')); // "Symbol(test)"
toSafeString(10n); // "10n"
toSafeString(new Date()); // "2026-08-19T..."
toSafeString(new Error('oops')); // "Error: oops"
const circular = {};
circular.self = circular;
toSafeString(circular); // '{"self":"[Circular]"}'Why not just String(value)?
- Objects often just produce
"[object Object]"withString(), instead of the actual structure. - Circular references crash a plain
JSON.stringify()call — here they're cleanly marked as"[Circular]". BigIntloses the fact that it was a BigInt withString()—to-safe-stringappends annsuffix.Errorobjects are formatted readably (Name: Message) instead of turning into an empty{}.
API
toSafeString(value: any): string
Takes any value and always returns a string — never throws.
License
MIT © Toby Maxham
