简体   繁体   English

如何在特定标签中使用正则表达式替换 html 属性

[英]How to replace html property using regex in a specific tag

I need to replace the value of "p-type" to "p-kind" only in the "button" tags using regex, for example:我只需要使用正则表达式将“p-type”的值替换为“p-kind”,例如:

input:输入:

<button p-type="foo">
    anything
</button>

output: output:

<button p-kind="foo">
    anything
</button>

the "p-type" property may not be the first one, but even then it should be changed to "p-kind", for example: “p-type”属性可能不是第一个,但即便如此也应该改为“p-kind”,例如:

input:输入:

<button anythingProperty p-type="foo">
    anything
</button>

output: output:

<button anythingProperty p-kind="foo">
    anything
</button>

If the tag is not a button the "p-type" remains, for example a div with this property will not be changed.如果标签不是按钮,则“p-type”仍然存在,例如具有此属性的div将不会更改。

I can change using the following expression: (p-type)([a-zA-Z0-9:]*) .我可以使用以下表达式进行更改: (p-type)([a-zA-Z0-9:]*) But that changes for all and I would like to group only the ones that are <button></button>但这对所有人都发生了变化,我只想将那些<button></button>

 const input = `<button style="color:red;" data-type="foo">anything</button>`; const doc = new DOMParser().parseFromString(input, "text/html"); const btn = doc.querySelector("button"); btn.dataset.type = "bar"; console.log(btn.outerHTML)

Or, on order to modify the data attribute name completely, ie: change data-type="foo" into data-kind="foo" :或者,为了完全修改数据属性名称,即:将data-type="foo"更改为data-kind="foo"

 const input = `<button style="color:red;" data-type="foo">anything</button>`; const doc = new DOMParser().parseFromString(input, "text/html"); const btn = doc.querySelector("button"); const dataValue = btn.dataset.type; // store the old value delete btn.dataset.type; // delete old data attribute btn.dataset.kind = dataValue; // add new data attribute console.log(btn.outerHTML)

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

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