Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get a class name from html

I know my question might look like a duplication for this question, but its not
I am trying to match a class name inside html text that comes from the server as a template using JavsScript RegExp and replace it with another class name. here what the code looks like :

<div class='a b c d'></div>
<!-- or -->
<div class="a b c d"></div>
<!-- There might be spaces after and before the = (the equal sign) -->

I want to match the class "b" for example
with the highest performance possible

here is a regular expression I used but it's not working in all cases, and I don't know why :

  var key = 'b';
  statRegex = new RegExp('(<[\w+ class="[\\w\\s]*?)\\b('+key+')\\b([\\w\\s]*")');
  html.replace( statRegex,'SomeOtherClass');// I may be mistake by the way I am replacing it here
like image 378
Evan Lévesque Avatar asked May 15 '13 07:05

Evan Lévesque


2 Answers

Using a regex, this pattern should work for you:

var r = new RegExp("(<\\w+?\\s+?class\\s*=\\s*['\"][^'\"]*?\\b)" + key + "\\b", "i");
#                   Λ                                         Λ                  Λ
#                   |_________________________________________|                  |
#                           ____________|                                        |
# [Creating a backreference]                                                     |
# [which will be accessible]  [Using "i" makes the matching "case-insensitive".]_|
# [using $1 (see examples).]  [You can omit "i" for case-sensitive matching.   ]

E.g.

var oldClass = "b";
var newClass = "e";
var r = new RegExp("..." + oldClass + "...");

"<div class='a b c d'></div>".replace(r, "$1" + newClass);
    // ^-- returns: <div class='a e c d'></div>
"<div class=\"a b c d\"></div>".replace(r, "$1" + newClass);
    // ^-- returns: <div class="a e c d"></div>    
"<div class='abcd'></div>".replace(r, "$1" + newClass);
    // ^-- returns: <div class='abcd'></div>     // <-- NO change

NOTE:
For the above regex to work there must be no ' or " inside the class string.
I.e. <div class="a 'b' c d"... will NOT match.

like image 191
gkalpak Avatar answered Sep 18 '22 12:09

gkalpak


Test it here: https://regex101.com/r/vnOFjm/1

regexp: (?:class|className)=(?:["']\W+\s*(?:\w+)\()?["']([^'"]+)['"]

const regex = /(?:class|className)=(?:["']\W+\s*(?:\w+)\()?["']([^'"]+)['"]/gmi;
const str = `<div id="content" class="container">

<div style="overflow:hidden;margin-top:30px">
  <div style="width:300px;height:250px;float:left">
<ins class="adsbygoogle turbo" style="display:inline-block !important;width:300px;min-height:250px; display: none !important;" data-ad-client="ca-pub-1904398025977193" data-ad-slot="4723729075" data-color-link="2244BB" qgdsrhu="" hidden=""></ins>


<img src="http://static.teleman.pl/images/pixel.gif?show,753804,20160812" alt="" width="0" height="0" hidden="" style="display: none !important;">
</div>`;

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}`);
    });
}
like image 45
FDisk Avatar answered Sep 19 '22 12:09

FDisk