Regular expression to get a class name from html

前端 未结 5 1089
温柔的废话
温柔的废话 2021-01-13 09:39

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

5条回答
  •  臣服心动
    2021-01-13 10:32

    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 + "...");
    
    "
    ".replace(r, "$1" + newClass); // ^-- returns:
    "
    ".replace(r, "$1" + newClass); // ^-- returns:
    "
    ".replace(r, "$1" + newClass); // ^-- returns:
    // <-- NO change

    NOTE:
    For the above regex to work there must be no ' or " inside the class string.
    I.e.

    will NOT match.

提交回复
热议问题