javascript - regex to parse any css font - Stack Overflow

Just wondering if anyone has a tried & tested regex to parse a css font string into its various pie

Just wondering if anyone has a tried & tested regex to parse a css font string into its various pieces:

  • 12px arial
  • italic bold sans-serif
  • 12px/50px verdana
  • etc

Just wondering if anyone has a tried & tested regex to parse a css font string into its various pieces:

  • 12px arial
  • italic bold sans-serif
  • 12px/50px verdana
  • etc
Share Improve this question asked Apr 13, 2012 at 5:29 user578895user578895 1
  • possible duplicate of How to parse CSS font shorthand format – stema Commented Apr 13, 2012 at 5:57
Add a ment  | 

3 Answers 3

Reset to default 8

Answering my own question:

/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/i

which separates to:

var       parts = rx.exec( str )
  , fontStyle   = parts[1] || 'normal'
  , fontVariant = parts[2] || 'normal'
  , fontWeight  = parts[3] || 'normal'
  , fontSize    = parts[4]
  , lineHeight  = parts[5]
  , fontFamily  = parts[6]
  ;

And yes, I realize that's insane

you mean like this?

How to parse CSS font shorthand format

Alternatively, there is also JSCSSP, a JavaScript library for parsing CSS.

Just a little fix to support parsing fonts with numbers in the name, such as Font Awesome (ex. Font Awesome 5 Free).

This regex :

/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z0-9]+?)\s*$/i

which separates to:

    var       parts = rx.exec( str )
  , fontStyle   = parts[1] || 'normal'
  , fontVariant = parts[2] || 'normal'
  , fontWeight  = parts[3] || 'normal'
  , fontSize    = parts[4]
  , lineHeight  = parts[5]
  , fontFamily  = parts[6]
  ;

just edit the block of fontFamily rules like ([-,"\sa-z0-9]+?)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744136183a4560068.html

相关推荐

  • javascript - regex to parse any css font - Stack Overflow

    Just wondering if anyone has a tried & tested regex to parse a css font string into its various pie

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信