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!