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

使用JavaScript正则表达式替换| |之间的字符串

Hey there! Let's figure out why your regex isn't catching the middle "Level" string, and fix it up.

The Problem with Your Current Regex

Your existing regex /\|\s(\D*?)\|/g works by matching full | [content] | chunks. Here's where it breaks:

  • Once it matches | Experience Points |, it consumes that closing | character. The remaining string starts with Level | Proficiency Bonus |—there's no leading | before "Level" anymore (it was "eaten" by the first match), so the regex can't pick it up.
  • Also, \D*? only matches non-digit characters, which would break if any of your content included numbers (like actual level values later on).

Solution 1: Adjusted Regex with Lookarounds

We can use lookarounds to match content between pipes without consuming the pipes themselves. This way, every chunk between | gets targeted, even the middle ones. Here's the fix:

const originalStr = "| Experience Points | Level | Proficiency Bonus |";
const formattedStr = originalStr.replace(/(?<=\|)\s*(.*?)\s*(?=\|)/g, "&lt;span&gt;$1&lt;/span&gt;");

Let's break down the regex components:

  • (?<=\|): A positive lookbehind that checks for a | before the content, but doesn't consume it (so the next match can still use the following |).
  • \s*: Matches any leading/trailing spaces around the content (keeps them inside the span, just like your example expects).
  • (.*?): A non-greedy capture group that grabs everything between the pipes (works for any character, not just non-digits).
  • (?=\|): A positive lookahead that checks for a | after the content, again without consuming it.

This will produce your desired output:
&lt;span&gt; Experience Points &lt;/span&gt; &lt;span&gt; Level &lt;/span&gt; &lt;span&gt; Proficiency Bonus &lt;/span&gt;

Solution 2: Non-Regex Approach (Easier to Debug)

If regex feels overly complex, you can split the string, filter out empty segments, and wrap valid content in spans—this is more readable for edge cases:

const originalStr = "| Experience Points | Level | Proficiency Bonus |";
const result = originalStr
  .split('|')
  .filter(part => part.trim() !== '')
  .map(part => `&lt;span&gt;${part}&lt;/span&gt;`)
  .join(' ');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:13:11