1

I need to replace the value of "p-type" to "p-kind" only in the "button" tags using regex, for example:

input:

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

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:

input :

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

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.

I can change using the following expression: (p-type)([a-zA-Z0-9:]*). But that changes for all and I would like to group only the ones that are <button></button>

6
  • You do realize that p-type is an invalid HTML5 attribute, right? Use data-* attributes instead. Also, use a proper DOMParser, not RegExp. Commented Dec 8, 2022 at 18:33
  • 1
    You can use 2 capture groups (<button\b[^<>]* p-)type(="[^"]*"[^<>]*>) regex101.com/r/r8lmwD/1 and replace with $1kind$2 but consider using a dom parser. Commented Dec 8, 2022 at 18:37
  • @RokoC.Buljan thanks for the answer. This component I'm using is customized and it has this property Commented Dec 8, 2022 at 18:38
  • 1
    @ramosjc You are welcome, but consider using the answer of Roko C. Buljan instead. Commented Dec 8, 2022 at 18:49
  • 1
    Like 80% of Regex tagged questions, this is a possible XY problem. Commented Dec 8, 2022 at 18:51

1 Answer 1

5

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, i.e: change data-type="foo" into 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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but in this example you are changing the value of "data-type", but how would I change the name of the property instead of the value
@ramosjc refresh the page. I edited the answer meanwhile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.