Using Regex, how to select whole <p>....</p>
where a certain text (example, "hello world") is inside the <p>....</p>
. Your kind help requested.
Asked
Active
Viewed 50 times
-1

ConnorsFan
- 70,558
- 13
- 122
- 146

Amer Hamid
- 145
- 6
1 Answers
-1
This JS regex would work, using a group to capture the paragraph content and positive lookahead to match until the first </p>
, not eating the others:
/<p>\s*([\w\s]*hello world[\w\s]*)\s*(?=<\/p>)/gm
If you want to capture the <p>
tags too:
/(<p>\s*[\w\s]*hello world[\w\s]*\s*(?=<\/p>)<\/p>)/gm
And if your <p>
tags might have classes or spaces:
/(<\s*p[^>]*?>\s*[\w\s]*hello world[\w\s]*\s*(?=<\s*\/p\s*>)<\s*\/p\s*>)/gm
Here is an example capturing whole <p>
tags:
const html = document.getElementById('demo').innerHTML;
const regex = new RegExp(/(<\s*p[^>]*?>\s*[\w\s]*hello world[\w\s]*\s*(?=<\s*\/p\s*>)<\s*\/p\s*>)/gm);
let match = regex.exec(html);
console.log('Matches:');
while (match != null) {
console.log(match[1])
match = regex.exec(html);
}
<div id="demo">
<p class="p1">bla bla hello world bla</p>
<p >hello world</p>
<p>Paragraph not matching</p>
</div>
Here is a good online tool to test your regular expressions.
Hope that helps!

jo_va
- 13,504
- 3
- 23
- 47
` tag and getting its `.textContent`
– Nick Parsons Jan 27 '19 at 12:22hello world<\/p>/`?
– Bergi Jan 27 '19 at 12:25