1

Need regex to search font awesome icon name from string.

What i tried so far:

function myFunction() {
    var str = '<i class="fa fa-edit"></i>'; 
    var res = str.match(/'fa-'*/);
    return res;
}

My function should return "fa-edit" as icon name

What should be my regex to find name ??

mike_t
  • 2,484
  • 2
  • 21
  • 39
extjs user
  • 263
  • 7
  • 17

4 Answers4

3

I don't know what tool/language you are using for the regex, but here is general solution which should work in most places:

<i class="(?:.*\s)?([^"]*)"><\/i>

The last class inside the <i> tag should appear as the first capture group.

Demo

var str = '<i class="fa fa-edit"></i>'; 
var res = str.match(/<i class="(?:.*\s)?([^"]*)"><\/i>/);
console.log(res[1])

Code snippet taken from @mike_t

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

If i correctly assume you are using javascript, try this:

Note: i also added as leading characters space and single/double quote, in case the class is specified as ie. "fa-edit fa" or 'fa-edit fa'

var str = '<i class="fa fa-edit"></i>'; 
    var res = str.match(/.*[\ \"\']+(fa-[a-zA-z0-9]*).*/);
    console.log(res[1])
mike_t
  • 2,484
  • 2
  • 21
  • 39
1

Brief

Although regex seems like a fantastic idea, it can run into issues: H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ.

Yes, I know, if it's a known subset regex can be used; but it doesn't mean it should.

This answer provides a way of converting the string to a DOM element, obtaining the classes and parsing them for a class beginning with fa-


Code

var str = '<i class="fa fa-edit"></i>',
    parser = new DOMParser(),
    doc = parser.parseFromString(str, "text/xml");

var x = doc.firstChild.className
          .split(" ")
          .filter(String)
          .filter(function(e) {
            return e.startsWith("fa-");
          });

console.log(x);
ctwheels
  • 21,901
  • 9
  • 42
  • 77
0

This regex will do what the title asks for - find fontawesome icon names.

fa-[a-zA-Z0-9-]+

Example: https://regex101.com/r/zPuxg0/3

Note that it will also include modifiers such as fa-2x, fa-spin etc. So be sure to filter those out depending on your needs.

antriver
  • 848
  • 1
  • 10
  • 21