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

使用JavaScript将方括号内的指定字符串设置为加粗样式

实现方法

核心是用正则表达式匹配所有方括号包裹的内容,替换为加粗标签:

正则匹配规则

匹配模式:\[([^\]]+)\]

  • \[:匹配左方括号(转义是因为方括号在正则里是特殊字符)
  • ([^\]]+):捕获组,匹配所有非右括号的字符(即方括号内的内容)
  • \]:匹配右方括号

代码示例

JavaScript

const originalStr = "[Number] years of practice in accounting and financial administration. Showcased skills in [Area of Expertise]";
const formattedStr = originalStr.replace(/\[([^\]]+)\]/g, '<strong>$1</strong>');
// 输出结果:<strong>Number</strong> years of practice in accounting and financial administration. Showcased skills in <strong>Area of Expertise</strong>

Python

import re

original_str = "[Number] years of practice in accounting and financial administration. Showcased skills in [Area of Expertise]"
formatted_str = re.sub(r'\[([^\]]+)\]', r'<strong>\1</strong>', original_str)
// 输出结果:<strong>Number</strong> years of practice in accounting and financial administration. Showcased skills in <strong>Area of Expertise</strong>

可选:生成Markdown加粗格式

如果需要Markdown原生的加粗效果(而非HTML标签),只需把替换目标改成**$1**(JS)或**\1**(Python):

JavaScript示例

const formattedMarkdown = originalStr.replace(/\[([^\]]+)\]/g, '**$1**');
// 输出结果:**Number** years of practice in accounting and financial administration. Showcased skills in **Area of Expertise**

Python示例

formatted_markdown = re.sub(r'\[([^\]]+)\]', r'**\1**', original_str)
// 输出结果:**Number** years of practice in accounting and financial administration. Showcased skills in **Area of Expertise**

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:56:03