![](/img/trans.png)
[英]Find in string and from a list matching strings and replace with html tags
[英]Find and replace expression in a string with HTML tags
這是用包含標簽屬性的字符串替換 HTML 標簽的后續問題。
這次我想做相反的過程並將${something.foo.bar}
出現替換回<input type="button" disabled="" data-value="something.foo.bar" value="foo.bar" />
。 例如考慮這個字符串:
"the quick ${something.brown.fox} jumps over the ${something.lazy.dog}"
最終結果應該是:
the quick <input type="button" disabled="" data-value="something.brown.fox" value="brown.fox" /> jumps over the <input type="button" disabled="" data-value="something.lazy.dog" value="lazy.dog" />
請注意something.
是一個已知的前綴,將始終出現在大括號內,因此輸入data-value
應該是大括號之間的值,並且輸入value
屬性應該包含沒有前綴的值。
我試圖通過多個 Regex match
和replaceAll
鏈接來解決它,但沒有得到想要的結果。
幫助表示贊賞。
您可以簡單地使用String.replace來制作它:
const s = "the quick ${something.brown.fox} jumps over the ${something.lazy.dog}" const res = s.replace(/\\$\\{([^}]+)\\}/g, (x, y) => { const [prefix, ...rest] = y.split('.') return `<input type="button" disabled="" data-value="${y}" value="${rest.join('.')}" />` }) console.log(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.