【问题标题】:How to replace html property using regex in a specific tag如何在特定标签中使用正则表达式替换 html 属性
【发布时间】:2022-12-11 20:29:11
【问题描述】:

我只需要使用正则表达式将“p-type”的值替换为“p-kind”,例如:

输入:

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

输出:

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

“p-type”属性可能不是第一个,但即便如此也应该改为“p-kind”,例如:

输入 :

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

输出:

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

如果标签不是按钮,则“p-type”仍然存在,例如具有此属性的 div 将不会更改。

我可以使用以下表达式进行更改:(p-type)([a-zA-Z0-9:]*)。 但这对所有人都发生了变化,我只想将 &lt;button&gt;&lt;/button&gt; 分组

【问题讨论】:

  • 您确实意识到 p-type 是无效的 HTML5 属性,对吧?请改用 data-* 属性。此外,使用正确的 DOMParser,而不是 RegExp。
  • 您可以使用 2 个捕获组 (&lt;button\b[^&lt;&gt;]* p-)type(="[^"]*"[^&lt;&gt;]*&gt;) regex101.com/r/r8lmwD/1 并替换为 $1kind$2 但考虑使用 dom 解析器。
  • @RokoC.Buljan 感谢您的回答。我使用的这个组件是定制的,它有这个属性
  • @Thefourthbird 这显然有效。太感谢了!

标签: javascript html regex regex-group regexp-replace


【解决方案1】:

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)

或者,为了完全修改属性:

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)

【讨论】:

    【解决方案2】:

    要使用正则表达式仅在“按钮”标签中将“p-type”的值替换为“p-kind”,您可以使用以下模式:

    (<button[^>]*)p-type=([^"]*)"
    

    此模式匹配“按钮”标签,后跟零个或多个非“>”字符,然后是单词边界和字符串“p-type=”,后跟零个或多个非双引号字符。

    要替换匹配的字符串,您可以使用以下替换模式:

    $1p-kind=$2"
    

    此替换模式使用原始模式中捕获的组来创建新字符串。第一个捕获组是“button”标签,后跟字符串“p-kind=”,第二个捕获组是双引号之间的值。

    以下是使用替换方法和上述模式的 JavaScript 示例代码:

    let input = `<button p-type="foo">
        anything
    </button>
    <button anythingProperty p-type="foo">
        anything
    </button>
    <div p-type="foo">
        anything
    </div>`;
    
    let output = input.replace(/(<button[^>]*)p-type=([^"]*)"/g, "$1p-kind=$2"");console.log(output);
    

    此代码输出以下内容:

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

    如您所见,“p-type”属性仅在“button”标签中被替换。

    【讨论】:

    猜你喜欢
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多