-1

I want to get elements with content having class name beginning with specific word using regex without using querySelectorAll. For example :

I have two elements

<h1 class="school">Primary</h1>
<h1 class="school project">Secondary</h1>

function match(className)   {
   regex =  new RegExp(/<([^\s]+).*?class="school".*?>(.+?)<\/\1>/gi);
   matches = data.match(regex);
   return matches
}

this regex only match with the first and not with second element having name "school project"

How to customize this regular expression that it will match all elements having class name beginning with specific name and how to concatenate the class name dynamically based on paramter className of match function in regex instead of hard coding it in regex

learner
  • 23
  • 1
  • 6
  • Why not just use something like `document.querySelectorAll("[class*=school]")`? As your code is set up right now, `school` and `project` are 2 different classes, so you could simply do `document.getElementsByClassName("school")` and get the same result. – Jesse Oct 04 '19 at 22:30
  • @Jesse It is a requirement to do it with regex – learner Oct 04 '19 at 22:31

1 Answers1

0

Maybe,

<(\S+).*?class="(?:\bschool\b.*?|.*?\bschool\b)".*?>(.+?)<\/\1>

might be just OK to look into.


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


const regex = /<(\S+).*?class="(?:\bschool\b.*?|.*?\bschool\b)".*?>(.+?)<\/\1>/gm;
const str = `<h1 class="school">Primary</h1>
<h1 class="school project">Secondary</h1>
<h2 class="project school">Primary</h2>
<h2 class="project school">Primary</h5>
<h3 class="schools project">Secondary</h3>`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Source

How can I concatenate regex literals in JavaScript?

Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    thanks, could you please also guide me how to concatenate class name as a string instead of hardcoding it as school for example const className = 'school' and then concatenate className in regex? – learner Oct 04 '19 at 23:24