Javascript插值-如何最好地替换包含字符串的变量中的项?

nr7wwzry  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(137)

因此,我们有一个经典的插值示例,如下所示:

const AGE = 25;
let result = `I'm ${AGE} years old!`;

我想实现的是在一个通过变量访问的字符串中替换,而不是直接替换。我从来不知道我必须替换多少项。例如:

const Item_Required = "The {item} is required and needs to be between {min} and {max} {unit}!"
const ContractTitle = "Contract Title"
const Unit_Characters = "characters";
let result = Item_Required
.replace("{item}", ContractTitle)
.replace("{min}", 3)
.replace("{max}", 100)
.replace("{unit}", Unit_Characters );

有没有更直接更好的方法来做到这一点?或者这就是应该走的路?

vuktfyat

vuktfyat1#

使用正则表达式替换很容易,您可以使用您喜欢的代码,但此代码不能出现在字符串中,例如${...}

const str = "The ${item} is required and needs to be between ${min} and ${max} ${unit}!"
const replacements={
    item : "Contract Title",
    unit : "characters",
    min: 3,
    max: 100,
}
const str2 = str.replace(/\$\{\w+\}/g, function(all) {
   return replacements[all.substring(2,all.length-1)] || all;
});
console.log(str)
console.log(str2);
qij5mzcb

qij5mzcb2#

JavaScript支持Tagged Template Literals。ES6中的原生函数是String.raw内置的Tag函数。但实际上,您可以创建自己的Tagged函数,并根据需要处理模板文字插值表达式:

const age = 25;
const min = 20;
const max = 30;

function ageTag(literals, age, min, max) {
  console.log(literals); // an array of literal strings in the template
  console.log(age); // first expression
  console.log(min); // second expression      
  console.log(max); // third expression

  if(age == 25) {
    age = 35
  }

  return `${literals[0]} really ${realAge}`;
} 

ageTag`my age is ${age} and the min allowed is ${min} and the max allowed is ${max}`

// =>
[
  'my age is ',
  ' and the min allowed is ',
  ' and the max allowed is ',
  ''
]
25
20
30
'my age is really 35'

相关问题