You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web Components正则需求:捕获模板插值但排除属性内实例(Lit)

问题:Web Components模板字符串中排除属性内的插值捕获

我正在开发Web Components,需要一个正则表达式来捕获模板字符串中的字符串插值实例。例如针对以下字符串:

<img src="${this.image}"/><h5>${this.title}</h5><p>${this.description}</p>

字符串插值实例位于${}中,原本可以用(this(\.\w+))捕获,但我不想捕获第一个处于属性内的实例。

我尝试过表达式((?<!".+)this(\.\w+)+(?!.+")),它在多行字符串(每个标签单独一行)中有效,但在单行字符串里无效。

补充说明

为简化问题我之前未提及,我正在使用Lit框架开发Web Components,已创建一个返回Lit TemplateResult的插值函数,现在想用<b>标签高亮数据,因此想将正则匹配项替换为unsafeHTML指令,但unsafeHTML在属性内使用会报错。以下是我的插值函数:

export function FillTemplate(templateString: string, data: any): TemplateResult {
    let regex = /((?<!".+)this(\.\w+)+(?!.+"))/g;
    if (regex.test(templateString)) {
        templateString = templateString.replace(/((?<!".+)this(\.\w+)+(?!.+"))/g, "unsafeHTML($1)");
    }
    return new Function('html', 'unsafeHTML', "return html`"+templateString +"`;").call(data, html, unsafeHTML);
};

我也在考虑,或许测试对象键而非模板字符串会是更好的方案。

内容的提问来源于stack exchange,提问作者Luke T O'Brien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:41:05