简体   繁体   中英

Replace HTML tag with string that contains tag attribute

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}

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;
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}")

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)

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