简体   繁体   中英

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. 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.

//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. Thanks!

Replacing value first time you assign new string to temporary variable newData = data.replace( {${input.id}} , input.value) . But on second loop you use old(unmodified) variable again. So it replaces the temporary variable's value with fresh one without first substitution. Se fixed code below. Pay attention newData initialized with data value, and only newData is used inside the loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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