How to convert a JavaScript Symbol to a string without the "Symbol(" prefix?

For example, if I use toString():

let s = Symbol('abc')
console.log(s.toString())

I get:

'Symbol(abc)'

How to get just the:

'abc'

part instead?

I know how to do this with string manipulation, but I would hope for a potentially more efficient solution that directly obtains the value.

I am using Symbol to implement an Enum: What is the preferred syntax for defining enums in JavaScript? and want to serialize it with a toJSON() on the containing class.

Tested in Node.js v10.15.1.

Upvotes: 3

Views: 1617

Answers (2)

Andrea
Andrea

Reputation: 6125

I would use s.description. It will return the description of the Symbol.

A deeper explanation here.

Upvotes: 5

abby37
abby37

Reputation: 647

Use description to get value

s.description

As when we create Symbol we pass description of that symbol.

For more read this.

Upvotes: 7

Related Questions