【JavaScript】动态修改字符串中某段文字的颜色

1,053 阅读1分钟

问题场景

在项目中某文本由后端接口返回,需要将此文本中的某字段设置为某颜色

解决

思路

  1. 将需要替换的文本设置为字符串数组
  2. 根据第1步的数组和对应文本需设置的颜色,设置以文本为key,以颜色为value的对象
  3. 循环数组,给数组中的文本根据第2步的对象匹配对应颜色,设置行内样式
  4. 利用正则将文本替换

代码

  • vue
  <div class="text" v-html="result-text"></div>
  • js
  handleStrColorReplace() {
    // 使用固定文本,假设此文本来源后端接口
    let text = '夕阳无限好,只是近黄昏';
    let replace_text =["夕阳","黄昏"];
    let color_dict = {'夕阳':'rgb(255,224,129)',"黄昏":"rgb(247,151,103)"};
    for(let i = 0;i<replace_text.length;i++) {
      let color_temp = color_dict[replace_text[i]]; // 当前文本对应的颜色
      let replaceStr ='<span style="color:' + color_temp + ';">' + replace_text[i] + "</span>";
      text = show_text.replace(RegExp(replace_text[i],'g'),replaceStr);
    }
    this.result_text = text;
  }