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

Angular 13中如何将字符串不规则片段替换为粗体文本?

Angular 13 实现字符串指定部分加粗的解决方案

正则表达式完全可以满足你的需求,结合PipeTransform能高效实现从API获取的字符串部分内容加粗效果,以下是具体实现步骤:

1. 创建自定义加粗管道(BoldPipe)

该管道会处理字符串中的标记内容,替换为<strong>标签,同时通过DomSanitizer确保HTML内容在Angular中安全渲染:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({ name: 'bold' })
export class BoldPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(text: string): SafeHtml {
    if (!text) return text;
    // 假设API返回的字符串用{{}}包裹需要加粗的内容,用正则替换为<strong>标签
    const processedText = text.replace(/{{(.*?)}}/g, '<strong>$1</strong>');
    return this.sanitizer.bypassSecurityTrustHtml(processedText);
  }
}

如果你的API返回的是原始字符串+加粗区间的起始/结束索引,可以修改管道的transform方法来支持索引参数:

transform(text: string, startIndex: number, endIndex: number): SafeHtml {
  if (!text || startIndex < 0 || endIndex > text.length) return text;
  const processedText = `${text.slice(0, startIndex)}<strong>${text.slice(startIndex, endIndex)}</strong>${text.slice(endIndex)}`;
  return this.sanitizer.bypassSecurityTrustHtml(processedText);
}

2. 在模块中声明管道

确保管道被添加到你的Angular模块的declarations数组中:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BoldPipe } from './bold.pipe';
import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, BoldPipe],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. 在模板中使用管道

根据你的数据格式选择对应的使用方式:

场景1:API返回带标记的字符串

如果API返回的字符串用{{}}标记了需要加粗的内容(例如"Whether it’s {{helping doctors detect diseases earlier}} or {{enabling people to access information}} in their own language"),模板中这样使用:

<ul>
  <li [innerHTML]="apiText1 | bold"></li>
  <li [innerHTML]="apiText2 | bold"></li>
  <li [innerHTML]="apiText3 | bold"></li>
</ul>

场景2:API返回原始字符串+加粗区间索引

如果API返回每个字符串对应的加粗起始/结束索引,模板中传入索引参数:

<ul>
  <li [innerHTML]="apiText1 | bold:10:45"></li>
  <li [innerHTML]="apiText2 | bold:16:48"></li>
  <li [innerHTML]="apiText3 | bold:22:55"></li>
</ul>

关键说明

  • 正则表达式的优势是可以批量处理统一标记的内容,适配你提到的“加粗位置各不相同”的场景;
  • 必须使用DomSanitizer绕过Angular的安全检查,否则<strong>标签会被过滤,无法渲染出粗体效果;
  • 如果需要基于语义规则(而非标记或索引)加粗内容,可以调整正则表达式匹配对应的文本模式(例如动词短语、特定术语等)。

内容的提问来源于stack exchange,提问作者EST203

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:33:19