你可以如何使用变量作为replaceAll()方法的模式和替换?

huangapple go评论55阅读模式
英文:

How can I use variables as the pattern and the replacement of replaceAll() method?

问题

我有一个表单,一旦点击提交按钮,就会生成一个对象。每个键值对都是按照这种模式构建的:inputId: inputValue,所以对象看起来像这样:

let inputsObj = {
   templateList: 'blank',
   agentsName: 'John',
   agentsPhone: '000-000-0000'
}

然后,我需要替换字符串中所有inputIds的实例。因此,字符串看起来像这样:

let template = "My name is agentsName and this is my phone number: agentsPhone"

我需要使它看起来像这样:

"My name is John and this is my phone number: 000-000-0000"

输入字段的数量是未知的(因为它取决于其他因素),它们不会总是相同的。因此,我正在尝试创建一个函数来动态替换这些占位符。我尝试遍历inputsObj,然后用其值替换每个键:

let finalTemplate

const getReplacements = () => {
   for (let replacement in inputsObj) {
       finalTemplate = template.replaceAll(replacement, inputsObj[replacement])
            return finalTemplate
   }
   return finalTemplate
}

例如,replacement 将是 agentsName,而 inputsObj[replacement] 应该是 John(它将遍历整个对象以获取所有键值对)。

但这不起作用。我猜这是因为我试图将变量用作模式和替换(当我尝试使用普通字符串时,它确实起作用,所以我知道其他一切都运作正常)。但我不知道如何解决这个问题。有什么想法吗?

编辑:
我尝试使用模板文字,但它没有起作用。

英文:

I have a form, and once the submit button is clicked, an object is generated. Each key-value pair is built following this pattern: inputId: inputValue, so the object looks like this:

let inputsObj = {
   templateList: 'blank',
   agentsName: 'John',
   agentsPhone: '000-000-0000'
}

I then need to replace all instances of the inputIds inside a string. So the string looks like this:

let template = "My name is agentsName and this is my phone number: agentsPhone"

and I need to make it look like this:

"My name is John and this is my phone number: 000-000-0000"

The number of input fields is unknown (since it depends on other things) and they won't always be the same. So I'm trying to create a function to replace these placeholders dynamically. I'm trying to loop through the inputsObj and then replace each key with its value:

let finalTemplate

const getReplacements = () => {
   for (let replacement in inputsObj) {
       finalTemplate = template.replaceAll(replacement, inputsObj[replacement])
            return finalTemplate
   }
   return finalTemplate
}

For example, replacement would be agentsName and inputsObj[replacement] should be John (and it would loop through the entire object in order to get all of the key-value pairs).

But this doesn't work. I'm guessing it's because I'm trying to use variables as the pattern and the replacement (it did work when I tried using regular strings instead, so I know everything else is working fine). But I don't know how to solve this. Any ideas?

EDIT:
I tried using template literals and it didn't work

答案1

得分: 1

你可以在你的示例中进行替换,你应该只在函数的最后返回结果:

let inputsObj = {
   templateList: 'blank',
   agentsName: 'John',
   agentsPhone: '000-000-0000'
}

let template = "My name is agentsName and this is my phone number: agentsPhone"

const getReplacements = () => {
   for (let replacement in inputsObj) {
        template = template.replaceAll(replacement, inputsObj[replacement])
   }
   return template
}

console.log(getReplacements());

或者,你可以使用 Object.keys 方法获取键的数组,并使用 reduce 来缩短语法:

let inputsObj = {
  templateList: 'blank',
  agentsName: 'John',
  agentsPhone: '000-000-0000'
};

let template = "My name is agentsName and this is my phone number: agentsPhone";

const getReplacements = () => Object.keys(inputsObj).reduce((acc, key) => acc.replaceAll(key, inputsObj[key]), template)

console.log(getReplacements())
英文:

You can make replacement like this in your example, you should only return the result at the end of your function:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let inputsObj = {
   templateList: &#39;blank&#39;,
   agentsName: &#39;John&#39;,
   agentsPhone: &#39;000-000-0000&#39;
}


let template = &quot;My name is agentsName and this is my phone number: agentsPhone&quot;

const getReplacements = () =&gt; {
   for (let replacement in inputsObj) {
        template = template.replaceAll(replacement, inputsObj[replacement])
   }
   return template
}

console.log(getReplacements());

<!-- end snippet -->

Alternatively you can get array of keys with Object.keys method and use reduce for shorter syntax:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let inputsObj = {
  templateList: &#39;blank&#39;,
  agentsName: &#39;John&#39;,
  agentsPhone: &#39;000-000-0000&#39;
};

let template = &quot;My name is agentsName and this is my phone number: agentsPhone&quot;;


const getReplacements = () =&gt; Object.keys(inputsObj).reduce((acc, key) =&gt; acc.replaceAll(key, inputsObj[key]), template)

console.log(getReplacements())

<!-- end snippet -->

答案2

得分: 1

  1. 你不能在循环的第一次迭代中返回
  2. 你必须在 finalTemplate 上使用 replaceAll
let inputsObj = {
  templateList: 'blank',
  agentsName: 'John',
  agentsPhone: '000-000-0000'
}

let template = "My name is agentsName and this is my phone number: agentsPhone"

const getReplacements = () => {
  let finalTemplate = template

  for (let replacement in inputsObj) {
    finalTemplate = finalTemplate.replaceAll(replacement, inputsObj[replacement])
  }
  return finalTemplate
}

console.log(getReplacements())
英文:
  1. You can't return in first iteration of the loop
  2. You have to use replaceAll on finalTemplate

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let inputsObj = {
  templateList: &#39;blank&#39;,
  agentsName: &#39;John&#39;,
  agentsPhone: &#39;000-000-0000&#39;
}

let template = &quot;My name is agentsName and this is my phone number: agentsPhone&quot;

const getReplacements = () =&gt; {
  let finalTemplate = template

  for (let replacement in inputsObj) {
    finalTemplate = finalTemplate.replaceAll(replacement, inputsObj[replacement])
  }
  return finalTemplate
}

console.log(getReplacements())

<!-- end snippet -->

答案3

得分: 0

只需使用模板文字来实现这个功能。

let inputsObj = 
  { templateList : 'blank'
  , agentsName   : 'John'
  , agentsPhone  : '000-000-0000'
  };

const getReplacements = ({agentsName, agentsPhone}) => 
  `My name is ${agentsName} and this is my phone number: ${agentsPhone}`;

console.log(getReplacements(inputsObj))
英文:

Simply use template littérals for that

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let inputsObj = 
  { templateList : &#39;blank&#39;
  , agentsName   : &#39;John&#39;
  , agentsPhone  : &#39;000-000-0000&#39;
  };

const getReplacements = ({agentsName, agentsPhone}) =&gt; 
  `My name is ${agentsName} and this is my phone number: ${agentsPhone}`;


console.log(getReplacements(inputsObj))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月27日 02:01:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定