CSS Style Parser
style-parser is a lightweight JavaScript library designed for parsing inline CSS style strings into structured JavaScript objects. It is built upon the `Parsimmon` parser combinator library, providing a robust and pure JavaScript solution for extracting style properties. The library is particularly useful in server-side environments with tools like Cheerio or within browser contexts where direct manipulation of string-based `style` attributes is required. The current stable version is 1.1.1. Its key differentiator is the ability to transform a raw CSS style string, such as `"font-size:13px;width:50px"`, into a usable JavaScript object like `{'font-size': '13px', 'width': '50px'}`, which is functionality not natively provided by jQuery or Cheerio's `attr('style')` method. The package's release cadence is not explicitly stated in the provided documentation.
Install
-
npm install style-parser -
yarn add style-parser -
pnpm add style-parser
Imports
- parse
import parse from 'style-parser';
const parse = require('style-parser');
Quickstart
const parse = require('style-parser');
const cheerio = require('cheerio'); // Install with 'npm install cheerio' for this example
// Basic usage: parse a simple inline style string
const styleString = 'font-size:13px;color:blue;';
const parsedStyle = parse(styleString);
console.log('Parsed simple style string:', parsedStyle);
// Expected: { 'font-size': '13px', color: 'blue' }
// Advanced usage: integrate with Cheerio to parse style attributes from HTML
const html = '<div style="width:100px;height:50px;border:1px solid #ccc;">Content</div>';
const $ = cheerio.load(html);
const inlineStyleAttr = $('div').attr('style');
if (inlineStyleAttr) {
const parsedCheerioStyle = parse(inlineStyleAttr);
console.log('Parsed style attribute from Cheerio element:', parsedCheerioStyle);
// Expected: { width: '100px', height: '50px', border: '1px solid #ccc' }
} else {
console.log('No style attribute found on the div element.');
}
// Handle cases where the style attribute might be undefined or empty
const emptyStyleHtml = '<div>No style</div>';
const $empty = cheerio.load(emptyStyleHtml);
const emptyInlineStyle = $empty('div').attr('style');
const parsedEmpty = parse(emptyInlineStyle || ''); // Ensure a string is passed
console.log('Parsed empty or missing style attribute:', parsedEmpty);
// Expected: {} (or similar empty object if input is null/undefined/empty string)