簡體   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