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

如何使用TypeScript为字符串中<自定义字符串>格式内容添加code标签

TypeScript实现方案

核心逻辑是通过正则匹配所有符合&lt;xxx&gt;格式的子串,批量替换为前后包裹code标签的格式即可,代码如下:

/**
 * 将字符串中所有 &lt;xxx&gt; 格式的内容前后包裹code标签
 * @param input 从API获取的原始字符串
 * @returns 处理后的字符串
 */
function wrapTagContentWithCode(input: string): string {
    // 正则规则:匹配所有以 &lt; 开头、&gt; 结尾,中间不含&的连续内容
    const matchReg = /&lt;[^&]+&gt;/g
    return input.replace(matchReg, (matchedStr) => `<code>${matchedStr}</code>`)
}

使用示例

// 模拟从API拿到的原始字符串
const rawStr = `The CSS &lt;background-color&gt; property defines the background color of an element.The &lt;push&gt; method adds one or more elements to the end of an &lt;array&gt; and returns the new length of the array.`

const processedStr = wrapTagContentWithCode(rawStr)
console.log(processedStr)

输出结果

The CSS <code>&lt;background-color&gt;</code> property defines the background color of an element.The <code>&lt;push&gt;</code> method adds one or more elements to the end of an <code>&lt;array&gt;</code> and returns the new length of the array.

如果你需要单独提取所有处理后的标签内容,可以使用下面的方法:

function extractWrappedCodeList(input: string): string[] {
    const matchReg = /&lt;[^&]+&gt;/g
    const matchResult = input.match(matchReg) || []
    return matchResult.map(item => `<code>${item}</code>`)
}

// 调用后返回的数组就是你给出的示例输出
// [
//   "<code>&lt;background-color&gt;</code>",
//   "<code>&lt;push&gt;</code>", 
//   "<code>&lt;array&gt;</code>"
// ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 23:39:01