循环字符串,向字符串添加单词,返回字符串

2023-12-11

我有一个纯文本对象。我还有一系列对象。在该对象数组中,每个对象都包含偏移量和长度键。

我想循环遍历我的纯文本字符串,将正确的单词插入到字符串中的某些偏移处,然后返回该字符串。

下面是我的代码

const plainText = "Hey name your food is ready, , your food has your name on it"

预期产出低于

mergeValues = [
{message: "Hey Keith your salmon is ready, your food has your name on it"},
{message: "Hey Kelly your pizza is ready, your food has your name on it"},
{message: "Hey Ed your hamburger is ready, your food has your name on it"},
{message: "Hey Shelby your sushi is ready, your food has your name on it"}
]
const people = [
{ name: "keith", food: "salmon"},
{ name: "kelly", food: "pizza"},
{ name: "ed", food: "hamburger"},
{ name: "shelby", food: "sushi"}
]
const locations = [
 {offset: 4, length: 4, field: 'name'},
 {offset: 13, length: 4, field: 'food'}
]

在这里,我在人员上进行映射,创建一个对象,然后在位置上运行 forEach,最后将该对象返回到地图以让它在人员数组中的下一个人上再次运行。 我很确定我的主要问题是我每次在 forEach 循环中重写对象,而不是修改字符串,保存该值,然后再次修改该字符串,保存值等等......

const mergeValues = people.map((person) => { 
    const messageObj = {message: ""};
    locations.forEach((location) => { 
        if(Object.keys(person).includes(location.field)) { 
            messageObj.message = plainText.substring(0, location.offset + 1) + person[location.field] + plainText.substring(location.length + location.offset + 1, plainText.length)
        } 
    }) 
return messageObj


如果您可以更改纯文本字符串以使用自定义变量,则可以创建自己的函数来使用正则表达式填充这些变量

const template =
  "Hey {name} your {food} is ready, your food has your name on it";

const variables = [
  { name: "keith", food: "salmon" },
  { name: "kelly", food: "pizza" },
  { name: "ed", food: "hamburger" },
  { name: "shelby", food: "sushi" }
];

function renderTemplate(template, variables) {
  let result = template;

  for (let [key, value] of Object.entries(variables)) {
    result = result.replace(new RegExp(`{${key}}`, "g"), value);
  }

  return result;
}

const results = variables.map((variableValues) =>
  renderTemplate(template, variableValues)
);

console.log(results);

通过这种方法,您甚至可以将相同的变量放在多个位置,您可以使用自己的语法控制变量位置({varName}在这种情况下)。

复杂性较低,您不需要计算位置,这种方法将使添加新变量变得更加困难。

const template = 
  "Hey {name} your {food} is ready, your food has your name on it - {name}"

将编译为

"Hey Keith your salmon is ready, your food has your name on it - Keith"

只是添加{name}到模板

代码沙箱:https://codesandbox.io/s/loving-cherry-jnwt5s?file=/src/index.js

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

循环字符串,向字符串添加单词,返回字符串 的相关文章

随机推荐