所以我的问题是如何在每个变量实例上用 backtick
拆分字符串。
我尝试使用 \${.*?}
但这不起作用,因为 ${variable}
将首先被变量值替换,然后拆分函数将被执行。
知道怎么做吗?
let a = 2
let b = 4
let x = `Superman${a}hello${b}one more`.split(/\${.*?}/g)
console.log(x)
另一方面:我不想要将它包装到 "或 ' 的解决方案。
console.log('`Superman${a}hello${b}one more`'.split(/\${.*?}/g))
最佳答案
该行执行后,无法获取原始模板字符串。但是,您可以使用标记函数/标记模板文字来获取字符串的各个部分,包括替换值:
function Test() {
console.log(arguments)
return arguments.length - 1
}
let a = 2
let b = 4
let c = Test `Superman${a}hello${b}one more`
console.log(`This template string has ${c} substituted values`)
关于javascript - 如何在 ${variable} 的每个实例上拆分 ``(反引号字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54579119/