例如...(这失败了)
\n\nconst currencyMap = {\r\n "$": "USD",\r\n "\xe2\x82\xac": "EUR",\r\n};\r\n\r\nconst r = \'$100\'.replace(/(\\$)([0-9]*)/g, `${currencyMap[$1]}$2`);\r\nconsole.log(r);Run Code Online (Sandbox Code Playgroud)\r\n有没有办法让这种事情起作用? \n$1在字符串中使用时可用,但不能用作键。
不幸的是,不行,您必须使用替换函数:
\n\nconst currencyMap = {\r\n "$": "USD",\r\n "\xe2\x82\xac": "EUR",\r\n};\r\n\r\nconst r = \'$100\'.replace(/(\\$)(\\d*)/g, (_, $1, $2) => currencyMap[$1] + $2);\r\nconsole.log(r);Run Code Online (Sandbox Code Playgroud)\r\n另请注意,您可以使用\\d代替[0-9],它使正则表达式更易于阅读。
如果您实际上不需要第二组来做特殊的事情,您可以只回显对象中的匹配:
\n\nconst currencyMap = {\r\n "$": "USD",\r\n "\xe2\x82\xac": "EUR",\r\n};\r\n\r\nconst r = \'$100\'.replace(/[$\xe2\x82\xac]/g, match => currencyMap[match]);\r\nconsole.log(r);Run Code Online (Sandbox Code Playgroud)\r\n