本文介绍了我可以依靠ES6“Symbol”的字符串表示吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ES6应用程序,通过网络发送其一些数据。其中的一部分涉及以ES6 Symbol s实现的标识符。例如:

I'm working on an ES6 app that sends some of its data over the network. Part of this involves identifiers that are implemented as ES6 Symbols. For example:

const FOO = Symbol('foo');

调用 Foo.toString() code>符号(富)。当我通过网络传递这些,我想传递它只是 foo 。但是据我所知,没有办法从 Symbol(foo)中提取 foo 使用正则表达式(具体来说, / ^ Symbol\((。*)\)$ /

Calling Foo.toString() yields Symbol(foo). When I pass these over the network, I'd like to pass it as just foo. However, to my knowledge, there is no way to extract foo from Symbol(foo) other than to pull it out with a regular expression (specifically, /^Symbol\((.*)\)$/).

我是否应该依赖正则表达式始终匹配?或者ES6的未来更新是否可能会破坏?如果我不能依赖正则表达式匹配,那么我将通过电子邮件发送 Symbol(foo)

Should I rely on the regular expression always matching? Or is it possible that future updates to ES6 will break this? If I can't rely on the regex matching then I'll just send it over the wire as Symbol(foo).

推荐答案

根据它总是符号(+ description +)

Symbol.prototype.toString 从内部方法调用返回一个字符串 SymbolDescriptiveString(sym)

Symbol.prototype.toString returns a string from an internal method call to SymbolDescriptiveString(sym):

你使用

FOO.toString().slice(7, -1)

因为符号描述本身可以包含括号,换行符等。例如,正则表达式中的将不匹配换行符。

because a symbol description could itself contain parentheses, line breaks, etc. The . in the regular expression won’t match line breaks for example.

这篇关于我可以依靠ES6“Symbol”的字符串表示吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:25