如何使用TypeScript为字符串中<自定义字符串>格式内容添加code标签
TypeScript实现方案
核心逻辑是通过正则匹配所有符合<xxx>格式的子串,批量替换为前后包裹code标签的格式即可,代码如下:
/** * 将字符串中所有 <xxx> 格式的内容前后包裹code标签 * @param input 从API获取的原始字符串 * @returns 处理后的字符串 */ function wrapTagContentWithCode(input: string): string { // 正则规则:匹配所有以 < 开头、> 结尾,中间不含&的连续内容 const matchReg = /<[^&]+>/g return input.replace(matchReg, (matchedStr) => `<code>${matchedStr}</code>`) }
使用示例
// 模拟从API拿到的原始字符串 const rawStr = `The CSS <background-color> property defines the background color of an element.The <push> method adds one or more elements to the end of an <array> and returns the new length of the array.` const processedStr = wrapTagContentWithCode(rawStr) console.log(processedStr)
输出结果
The CSS <code><background-color></code> property defines the background color of an element.The <code><push></code> method adds one or more elements to the end of an <code><array></code> and returns the new length of the array.
如果你需要单独提取所有处理后的标签内容,可以使用下面的方法:
function extractWrappedCodeList(input: string): string[] { const matchReg = /<[^&]+>/g const matchResult = input.match(matchReg) || [] return matchResult.map(item => `<code>${item}</code>`) } // 调用后返回的数组就是你给出的示例输出 // [ // "<code><background-color></code>", // "<code><push></code>", // "<code><array></code>" // ]
内容的提问来源于stack exchange,提问作者Angel Reji
相关产品推荐
相关产品推荐

