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

无法通过NSHTMLTextDocumentType读取<strong>标签,内容无法加粗求助

解决代码无法识别<strong>标签并实现加粗效果的方案

嘿,我懂你的困扰——代码没法处理<strong>标签,没法把对应内容变成加粗效果对吧?下面给你针对不同场景的实用解决办法:

场景1:浏览器前端处理

如果你是在网页里需要把这段HTML文本转成带加粗效果的内容,有两种思路:

直接让浏览器渲染HTML

如果你的需求是在页面上显示加粗效果,不用转成Markdown,直接把文本插入到DOM元素里就行,浏览器会自动解析<strong>标签:

// 假设你有一个id为content的容器元素
const contentContainer = document.getElementById('content');
let txt = "<p><em>The first day of your <strong>Kerala tour itinerary</strong> starts with a trip along the winding roads to the beautiful hill station of Munnar</em></p>\r\n<p>Your holiday to the mesmerizing Munnar starts with a&nbsp;transfer from Cochin. Enjoy the picturesque hill-station as you drive through the serpentine roads surrounded by lush green hills. En...";

contentContainer.innerHTML = txt;

这样页面上的Kerala tour itinerary就会自动显示为加粗样式。

转成Markdown加粗格式

如果需要把<strong>标签替换成Markdown的**加粗语法,用正则表达式替换就很方便:

let txt = "<p><em>The first day of your <strong>Kerala tour itinerary</strong> starts with a trip along the winding roads to the beautiful hill station of Munnar</em></p>\r\n<p>Your holiday to the mesmerizing Munnar starts with a&nbsp;transfer from Cochin. Enjoy the picturesque hill-station as you drive through the serpentine roads surrounded by lush green hills. En...";

// 全局替换<strong>和</strong>为Markdown加粗符号,忽略标签大小写
const processedText = txt.replace(/<strong>(.*?)<\/strong>/gi, "**$1**");
console.log(processedText);

场景2:Node.js后端处理

如果是在Node.js环境下处理这段文本(没有浏览器DOM支持),可以用cheerio这个轻量的HTML解析库来处理,比正则更稳妥:

  1. 先安装cheerio:
npm install cheerio
  1. 然后编写处理代码:
const cheerio = require('cheerio');
let txt = "<p><em>The first day of your <strong>Kerala tour itinerary</strong> starts with a trip along the winding roads to the beautiful hill station of Munnar</em></p>\r\n<p>Your holiday to the mesmerizing Munnar starts with a&nbsp;transfer from Cochin. Enjoy the picturesque hill-station as you drive through the serpentine roads surrounded by lush green hills. En...";

// 加载HTML文本
const $ = cheerio.load(txt);

// 将所有<strong>标签替换为Markdown加粗格式
$('strong').replaceWith(function() {
  return `**${$(this).text()}**`;
});

// 获取处理后的文本
const result = $.html();
console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:23:20