如何用正则表达式移除自定义标签内部内容的首尾空白字符?
解决方案
你之前的正则问题在于匹配项包含了标签本身,直接替换为空会把标签一同删除,只要用捕获组保留标签部分,仅移除多余空白即可实现需求。
实现思路
我们可以分两步做全局替换:
- 匹配所有目标开标签后的连续空白,保留开标签删除空白
- 匹配所有目标闭标签前的连续空白,保留闭标签删除空白
默认支持你提到的<i>、<c>、<b1>、<b2>、<b3>,以及所有<key+数字>格式的关键词标签。
如果你示例中出现的
<b>标签也需要做相同处理,只需把正则的标签匹配规则修改为(<(i|c|b|b[1-3]|key\d+)>)即可。
完整代码
const content = `<b1> <c> "The Modern Amphibians" </c> </b1> Modern <b>amphibians </b> have a simplified <key2>anatomy </key2> compared to their ancestors due to <i> paedomorphosis</i>. Caused by two evolutionary trends: <b2> miniaturization </b2> and an unusually. Don’t think that this term’s work will be <key23> a piece of cake </key23>`; // 匹配开标签后空白的正则 const openTagRegex = /(<(i|c|b[1-3]|key\d+)>)\s+/g; // 匹配闭标签前空白的正则 const closeTagRegex = /\s+(<\/(i|c|b[1-3]|key\d+)>)/g; const output = content.replace(openTagRegex, '$1').replace(closeTagRegex, '$1');
运行后得到的output和你给出的期望效果完全一致,如需适配其他自定义标签,修改正则括号内的匹配规则即可。
内容的提问来源于stack exchange,提问作者schutte
相关产品推荐
相关产品推荐

