Home > Software design >  Replace HTML tag with string that contains tag attribute
Replace HTML tag with string that contains tag attribute

Time:11-01

consider this string:

the quick&nbsp;<input type="button" disabled="" value="brown.fox" />&nbsp;jumps over the&nbsp;<input type="button" disabled="" value="lazy.dog" />

I would like to replace every occurrence of the <input type="button" tag with a string that contains the value attribute of the tag, specifically with this string ${}

So the end result should be

the quick&nbsp;${brown.fox}&nbsp;jumps over the&nbsp;${lazy.dog}

CodePudding user response:

As you are in JavaScript, you have a DOM parser at your fingertips. Use it!

const input = `the quick&nbsp;<input type="button" disabled="" value="brown.fox" />&nbsp;jumps over the&nbsp;<input type="button" disabled="" value="lazy.dog" />`;
const container = document.createElement('div');
container.innerHTML = input;
const buttons = container.querySelectorAll("input[type=button]");
buttons.forEach(button=>{
  button.replaceWith("${" button.value "}");
});
const output = container.innerHTML;

CodePudding user response:

let text = 'the quick&nbsp;<input type="button" disabled="" value="brown.fox" />&nbsp;jumps over the&nbsp;<input type="button" disabled="" value="lazy.dog" />';

text = text.replace(/<input[^>]*value\s*=\s*["'](. ?)["']\s*[^>]*>/g,"${$1}")

CodePudding user response:

You need to use regex for this.

This code should work:

a = 'the quick&nbsp;<input type="button" disabled="" value="brown.fox" />&nbsp;jumps over the&nbsp;<input type="button" disabled="" value="lazy.dog" />'

pattern = /<input type=\"button\".*?value=\"([^\"] )\" \/>/gm

matches = a.matchAll(pattern);
    
for (const match of matches) {
  a = a.replace(match[0], "${"   match[1]   "}")
}

console.log(a)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related