繁体   English   中英

用包含标签属性的字符串替换 HTML 标签

[英]Replace HTML tag with string that contains tag attribute

考虑这个字符串:

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

我想用包含标签的 value 属性的字符串替换<input type="button"标签的每次出现,特别是用这个字符串${}

所以最终的结果应该是

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

正如您在 JavaScript 中一样,您有一个触手可及的 DOM 解析器。 用它!

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

您需要为此使用正则表达式。

此代码应该工作:

 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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