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

发布于 2025-01-17 12:39:34 字数 1468 浏览 0 评论 0原文

我有一个明文对象。我也有一系列对象。在那个对象数组中,每个对象都包含偏移键和长度键。

我想在我的明文字符串上循环,将适当的单词插入某些偏移的字符串中,然后返回该字符串。

代码

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,最后将该对象返回地图,以使其再次在People Array中的下一个人上运行。 我很确定我的主要问题是我每次在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

I have a plainText object. I also have an array of objects. In that array of objects, each object contains offset and length keys.

I want to loop over my plainText string, insert the proper words into the string at certain offsets and then return that string.

Here is my code below

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

expected output below

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'}
]

Here I am mapping over people, creating an object, then running a forEach on locations, and finally returning that object back to the map to let it run again on the next person in people array.
Im pretty sure my main issue is that I am Rewriting over the object everytime in the forEach loop instead of modifying the string, saving that value, then modifying that string again, saving value etc.....

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

毁梦 2025-01-24 12:39:34

如果您可以更改使用自定义vars的明文字符串,则可以创建自己的函数以使用

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);

此方法的正则表达式填充这些var,甚至可以在多个位置放置相同的变量,您可以使用自己的语法控制变量位置(<<<<代码> {varname} 在这种情况下)。

较少的复杂性,您不需要计算位置,该方法将使添加新的Vars更加困难。

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}添加到模板

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

If you can change the plainText string to use custom vars, you can create your own function to fill those vars using regular expressions

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);

With this approach you can even put the same variable in multiple places, you control the variable location using your own syntaxs ({varName} in this case).

Less complexity, you don't need to count positions, that approach will make adding new vars harder.

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

Will compile to

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

just adding {name} to the template

CodeSandbox: https://codesandbox.io/s/loving-cherry-jnwt5s?file=/src/index.js

云裳 2025-01-24 12:39:34

您的解决方案非常复杂,请尝试使用 String.replace,如下所示:

    const mergeValues = people.map((person) => { 
        const messageObj = {message: plainText};
        for(const key in person){
            messageObj.message = messageObj.message.replace(key, person[key])
        }
    return messageObj
})

Your solution is pretty complex, try with String.replace, like this:

    const mergeValues = people.map((person) => { 
        const messageObj = {message: plainText};
        for(const key in person){
            messageObj.message = messageObj.message.replace(key, person[key])
        }
    return messageObj
})
挖鼻大婶 2025-01-24 12:39:34

您只需使用 map减少替换以实现结果为:

const plainText = 'Hey name your food is ready';

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: 14, length: 4, field: 'food' },
];

const mergeValues = people.map((person) => {
  return locations.reduce((acc, { field }) => {
    return acc.replace(field, person[field]);
  }, plainText);
});

console.log(mergeValues);

You can simply use map, reduce and replace to achieve the result as:

const plainText = 'Hey name your food is ready';

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: 14, length: 4, field: 'food' },
];

const mergeValues = people.map((person) => {
  return locations.reduce((acc, { field }) => {
    return acc.replace(field, person[field]);
  }, plainText);
});

console.log(mergeValues);

守护在此方 2025-01-24 12:39:34

你可以用替换来尝试一下。

const plainText = "Hey name your food 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: 14, length: 4, field: 'food'}
]
    
const mergeValues = people.map((person) => { 
    let plainTextLength = plainText.length;
    let messageObj = {message:plainText};
    locations.map((location) => { 
        let lengthOffset = 0;
        if(messageObj.message.length > plainTextLength){
            lengthOffset = messageObj.message.length - plainTextLength;
            messageObj.message = messageObj.message.replace(messageObj.message.substring(location.offset + lengthOffset, location.offset + location.length + lengthOffset), person[location.field]);
        } else if (messageObj.message.length < plainTextLength) {
             lengthOffset = plainTextLength - messageObj.message.length;
            messageObj.message = messageObj.message.replace(messageObj.message.substring(location.offset - lengthOffset, location.offset + location.length - lengthOffset), person[location.field]);
        } else {
             messageObj.message = messageObj.message.replace(messageObj.message.substring(location.offset, location.offset + location.length), person[location.field]);
        }
    })
return messageObj
});

console.log(mergeValues);

You can try this with replace.

const plainText = "Hey name your food 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: 14, length: 4, field: 'food'}
]
    
const mergeValues = people.map((person) => { 
    let plainTextLength = plainText.length;
    let messageObj = {message:plainText};
    locations.map((location) => { 
        let lengthOffset = 0;
        if(messageObj.message.length > plainTextLength){
            lengthOffset = messageObj.message.length - plainTextLength;
            messageObj.message = messageObj.message.replace(messageObj.message.substring(location.offset + lengthOffset, location.offset + location.length + lengthOffset), person[location.field]);
        } else if (messageObj.message.length < plainTextLength) {
             lengthOffset = plainTextLength - messageObj.message.length;
            messageObj.message = messageObj.message.replace(messageObj.message.substring(location.offset - lengthOffset, location.offset + location.length - lengthOffset), person[location.field]);
        } else {
             messageObj.message = messageObj.message.replace(messageObj.message.substring(location.offset, location.offset + location.length), person[location.field]);
        }
    })
return messageObj
});

console.log(mergeValues);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文