首页 > 解决方案 > 有没有更快的方法在字符串中找到占位符模板

问题描述

我有这样的字符串:

This is item: {item.ITEMNAME} and it's width is: {item.ITEMWIDTH}...

我需要获取所有这些占位符,但现在我正在手动进行,例如:

if (indexOf('{item.') > 0) {
  // get a list of all placeholders
  // Loop through all and try to replace
}

这可能很慢,有没有办法让它更通用并提取所有内容:

let array = string.find('{item.???}');

标签: javascriptstringecmascript-6replace

解决方案


你能在每个左花括号前附加一个美元符号吗?

然后你可以使用 ES6模板文字

let item = {
  ITEMNAME : 'Foo',
  ITEMWIDTH : '100%'
}

let str = `This is item: ${item.ITEMNAME} and its width is: ${item.ITEMWIDTH}...`

console.log(str)


推荐阅读