For example, if I use toString()
:
let s = Symbol('abc')
console.log(s.toString())
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.
Share Improve this question edited Oct 22, 2019 at 8:17 Ciro Santilli OurBigBook. asked Oct 22, 2019 at 8:14 Ciro Santilli OurBigBook.Ciro Santilli OurBigBook. 385k117 gold badges1.3k silver badges1.1k bronze badges 3-
.slice
the string? – CertainPerformance Commented Oct 22, 2019 at 8:15 - @CertainPerformance I would hope for a solution that does not involve possibly inefficient string manipulation. – Ciro Santilli OurBigBook. Commented Oct 22, 2019 at 8:16
- Slicing a string isn't inefficient at all. If you're running into performance issues, run a performance test to identify parts of your script that are taking up resources - string slicing will almost certainly not be one of them. (Worrying about it is quite premature optimization) – CertainPerformance Commented Oct 22, 2019 at 8:17
2 Answers
Reset to default 7Use description to get value
s.description
As when we create Symbol we pass description of that symbol.
For more read this.
I would use s.description
. It will return the description of the Symbol
.
A deeper explanation here.