Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

How can I match a bunch of p tags at the end of an html document with javascript regex?

Here is a sample content:

<p> so so so </p>
<div> whatever</div
<p> another paragraph </p>
<div> forever </div>
<p> first of last </p>
<p> second of last </p>

How can I match the last two paragraphs (or any number of consecutive paragraphs) at the end of the above document?

The match output I want is:

<p> first of last </p>
<p> second of last </p>

I tried /(<p>[sS]*?</p>[s]*)$/g, but the lazy matching is not working as expected, it sucks all the p tags in between, and matches from the first opening p tag it encounters up to the end of the document.

Note: there might not be paragraphs at the end at all, the regex should not match if there are no paragraphs at the end.

question from:https://stackoverflow.com/questions/65852603/how-can-i-match-a-bunch-of-p-tags-at-the-end-of-an-html-document-with-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here we use regex to match all paragraphs and then take the last two elements of the result array.

let str = `<p> so so so </p>
<div>
whatever
</div
<p> another paragraph </p>
<div> forever </div>
<p> first of last </p>
<p> second of last </p>`

let reg = /<p>[ws]*</p>/g;

let res = str.match(reg);

console.log(res[res.length-2]);
console.log(res[res.length-1]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...