[英]Replace HTML tag with string that contains tag attribute
考虑这个字符串:
the quick <input type="button" disabled="" value="brown.fox" /> jumps over the <input type="button" disabled="" value="lazy.dog" />
我想用包含标签的 value 属性的字符串替换<input type="button"
标签的每次出现,特别是用这个字符串${}
所以最终的结果应该是
the quick ${brown.fox} jumps over the ${lazy.dog}
正如您在 JavaScript 中一样,您有一个触手可及的 DOM 解析器。 用它!
const input = `the quick <input type="button" disabled="" value="brown.fox" /> jumps over the <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 <input type="button" disabled="" value="brown.fox" /> jumps over the <input type="button" disabled="" value="lazy.dog" />';
text = text.replace(/<input[^>]*value\s*=\s*["'](.+?)["']\s*[^>]*>/g,"${$1}")
您需要为此使用正则表达式。
此代码应该工作:
a = 'the quick <input type="button" disabled="" value="brown.fox" /> jumps over the <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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.