Suppose I have a symbol such as const sym = Symbol('foo');
. Now, is there a way to get the value foo
from that symbol without relying on string manipulations?
I expected sym.toString()
to return 'foo'
but it returns Symbol(foo)
.
I settled with this hacky solution, until I find a better one :)
const key = Symbol.keyFor(sym) || (sym = sym.toString(), sym.substring(7, sym.length - 1));
There is the Symbol.keyFor
. But it only works with the globally registered symbols
const works = Symbol.for('foo');
const key1 = Symbol.keyFor(works); // "foo"
const doesNotWork = Symbol('foo');
const key2 = Symbol.keyFor(doesNotWork); // undefined
I'm guessing that the private symbols do this by design. You could always monkey patch it:
const patched = Symbol('foo');
patched.key = 'foo';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With