简体   繁体   English

替换字符串中的多个子字符串-Javascript

[英]replacing multiple substrings in a string - Javascript

I've got a question I am just stumped on. 我有一个问题很困扰。 I am trying to replace multiple different substrings in a string. 我正在尝试替换字符串中的多个不同子字符串。 The webpage consists of a javascript object code snippet in between code tags. 该网页由位于code标签之间的javascript对象代码段组成。 The user should be able to type into an input, click submit, and replace the corresponding value on the object. 用户应该能够键入输入,单击提交,然后替换对象上的相应值。 The keys on the object match the id on the input. 对象上的键与输入上的ID匹配。

//get all inputs on the page
let inputs = Array.from(document.getElementsByTagName('input'))

//content that appears in the <code> tags
let data = `data: {
    First_Name: '{First_Name}',
    Last_Name: '{Last_Name}'
},`

//set that content to the innerHTML
$('code').html(data)

$('button').click(function() {
    var newData = '';
    inputs.forEach(input => {
        if(data.includes(input.id)) {
           newData = data.replace(`{${input.id}}`, input.value)
        }
})

console.log(newData)
    /*
    returns let data = `data: {
    First_Name: '{First_Name}',
    Last_Name: 'Smith'
    },`
    */
})

This is about as far as I have gotten. 据我所知。 I understand that this line 我了解这条线

newData = data.replace(`{${input.id}}`, input.value)

returns a new string, and it seems to be replacing the first name, then going back and replacing the last name in the original string and returning that. 返回一个新的字符串,它似乎将替换名字,然后返回并替换原始字符串中的姓氏并返回。 So there is some key to accomplishing this that I am missing or a totally better way of doing it. 因此,实现这一目标的关键是我所缺少的或者是一种更好的实现方式。 I appreciate any help, let me know if I should put up a jsfiddle example or something. 感谢您的帮助,请告诉我是否应该举一个jsfiddle示例或其他内容。 Thanks! 谢谢!

Replacing value first time you assign new string to temporary variable newData = data.replace( {${input.id}} , input.value) . 第一次替换值时,将新字符串分配给临时变量newData = data.replace( {$ {input.id}} , input.value) But on second loop you use old(unmodified) variable again. 但是在第二个循环中,您再次使用了old(unmodified)变量。 So it replaces the temporary variable's value with fresh one without first substitution. 因此,它无需重新替换就用新的临时变量替换了临时变量的值。 Se fixed code below. Se下面的固定代码。 Pay attention newData initialized with data value, and only newData is used inside the loop. 注意用data值初始化的newData ,并且循环内仅使用newData

$('button').click(function() {
    var newData = data;
    inputs.forEach(input => {
        if(data.includes(input.id)) {
           newData = newData.replace(`{${input.id}}`, input.value)
        }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM