使用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
相关产品推荐
相关产品推荐

