JavaScript中替换以分号结尾的<p>标签为<li>标签的技术咨询
Got it, let's fix this regex and get the replacement working exactly how you need it.
The Correct Regular Expression & Implementation
You were on the right track with your initial regex—we just need to tweak it to properly capture the content before the trailing semicolon and target the full closing </p> tag. Here's the working code:
const originalContent = '<p>one</p> <p>two</p> <p>three;</p> <p>four;</p> <p>five</p>'; const modifiedContent = originalContent.replace(/<p>(.*?);<\/p>/g, '<li>$1</li>'); console.log(modifiedContent); // Output: <p>one</p> <p>two</p> <li>three</li> <li>four</li> <p>five</p>
Breakdown of the Regex
Let's break down why this works:
<p>: Matches the opening paragraph tag exactly.(.*?): A non-greedy capture group that grabs all content inside the<p>tag until it hits the trailing semicolon—this ensures we don't accidentally match across multiple tags.;</p>: Matches the semicolon followed immediately by the closing</p>tag, confirming this is a paragraph we want to replace./g: The global flag, which makes sure we replace all matching<p>tags in the string, not just the first one.
Notes on Edge Cases
- This won't affect
<p>tags where the semicolon isn't at the very end of the content (like<p>hello;world</p>)—which aligns with your requirement to only target tags where the content ends with a semicolon. - If your content might have whitespace between the semicolon and
</p>(like<p>three; </p>), you can adjust the regex to account for that:/<p>(.*?);\s*<\/p>/g(the\s*matches any number of whitespace characters).
内容的提问来源于stack exchange,提问作者user8980530
相关产品推荐
相关产品推荐

