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

如何使用JavaScript在段落中将单个单词加粗且不拆分段落?

单段落内单词加粗的实现方案

你当前写法的问题在于<p>是块级元素,浏览器解析到连续的<p>标签时会自动拆分段落,无法得到单个段落内包含加粗文本的效果。用JavaScript处理的实现方法如下:


方法1:DOM节点操作(直接操作页面现有元素)

// 提取原结构里的普通文本和加粗文本
const normalText = document.querySelector('p:first-of-type').textContent.trim();
const boldText = document.querySelector('strong p').textContent.trim();

// 生成新的单个p标签
const newParagraph = document.createElement('p');
// 插入普通文本
newParagraph.append(`${normalText} `);
// 插入加粗节点
const boldNode = document.createElement('strong');
boldNode.textContent = boldText;
newParagraph.append(boldNode);

// 替换页面原有拆分的结构
const oldSnippetContainer = document.querySelector('.snippet');
oldSnippetContainer.parentNode.replaceChild(newParagraph, oldSnippetContainer);

处理后生成的DOM结构为:
<p>Next word is bold <strong>Bold</strong></p>
完全符合你要的单个段落、指定单词加粗的需求,不需要额外追加无关内容。


方法2:HTML字符串处理(适用于直接处理代码字符串的场景)

// 你当前的原始HTML字符串
const originHtml = `<p>Next word is bold</p><strong><p>Bold</p></strong>`;

// 匹配提取两段文本
const matchResult = originHtml.match(/<p>([^<]+)<\/p><strong><p>([^<]+)<\/p><\/strong>/);
const normalText = matchResult[1];
const boldText = matchResult[2];

// 拼接生成目标HTML字符串
const targetHtml = `<p>${normalText} <strong>${boldText}</strong></p>`;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:54:04