Socket
Socket
Sign inDemoInstall

posthtml-attrs-parser

Package Overview
Dependencies
Maintainers
2
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

posthtml-attrs-parser - npm Package Compare versions

Comparing version 0.1.1 to 1.0.0

lib/index.js

142

lib/attr.js

@@ -1,101 +0,73 @@

'use strict';
export function parseAttr(attrStr, rule) {
rule = rule || {};
const delimiter = rule.delimiter;
const keyDelimiter = rule.keyDelimiter;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseAttr = parseAttr;
exports.stringifyAttr = stringifyAttr;
function parseAttr(attrStr, rule) {
rule = rule || {};
var delimiter = rule.delimiter;
var keyDelimiter = rule.keyDelimiter;
if (!delimiter && !keyDelimiter) {
return attrStr;
if (!delimiter && !keyDelimiter) {
return attrStr;
}
const attrValues = delimiter ? attrStr.split(delimiter) : [attrStr];
if (!keyDelimiter) {
return attrValues;
}
const attrDict = {};
/**
* We need to split attrKeyValue by keyDelimiter only once.
* Therefore we use match() + slice() instead of split()
*/
attrValues.forEach(attrKeyValue => {
const match = attrKeyValue.match(keyDelimiter);
if (!match) {
return;
}
var attrValues = delimiter ? attrStr.split(delimiter) : [attrStr];
if (!keyDelimiter) {
return attrValues;
const attrKey = attrKeyValue.slice(0, match.index);
if (!attrKey) {
return;
}
var attrDict = {};
attrValues.forEach(function (attrKeyValue) {
// We need to split attrKeyValue by keyDelimiter only once.
// Therefore we use match() + slice() instead of split()
const attrValue = attrKeyValue.slice(match.index + match[0].length) || '';
let attrCombinedValue = attrDict[attrKey];
var match = attrKeyValue.match(keyDelimiter);
if (!match) {
return;
}
if (attrCombinedValue) {
if (! Array.isArray(attrCombinedValue)) {
attrCombinedValue = [attrCombinedValue];
}
var attrKey = attrKeyValue.slice(0, match.index);
if (!attrKey) {
return;
}
attrCombinedValue.push(attrValue);
} else {
attrCombinedValue = attrValue;
}
var attrValue = attrKeyValue.slice(match.index + match[0].length) || '';
var attrCombinedValue = attrDict[attrKey];
attrDict[attrKey] = attrCombinedValue;
});
if (attrCombinedValue) {
if (!Array.isArray(attrCombinedValue)) {
attrCombinedValue = [attrCombinedValue];
}
attrCombinedValue.push(attrValue);
} else {
attrCombinedValue = attrValue;
}
attrDict[attrKey] = attrCombinedValue;
});
return attrDict;
return attrDict;
}
function stringifyAttr(attr, rule) {
rule = rule || {};
var delimiter = (rule.glue || rule.delimiter || '').toString();
var keyDelimiter = (rule.keyGlue || rule.keyDelimiter || '').toString();
export function stringifyAttr(attr, rule) {
rule = rule || {};
const delimiter = (rule.glue || rule.delimiter || '').toString();
const keyDelimiter = (rule.keyGlue || rule.keyDelimiter || '').toString();
if (typeof attr === 'string') {
return attr;
}
if (typeof attr === 'string') {
return attr;
}
if (Array.isArray(attr)) {
return attr.join(delimiter);
}
if (Array.isArray(attr)) {
return attr.join(delimiter);
}
var attrKeyValues = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
const attrKeyValues = [];
for (let attrName of Object.keys(attr)) {
let attrCombinedValue = Array.isArray(attr[attrName]) ? attr[attrName] : [attr[attrName]];
try {
var _loop = function _loop() {
var attrName = _step.value;
attrCombinedValue.forEach(attrValue => {
attrKeyValues.push(attrName + keyDelimiter + attrValue);
});
}
var attrCombinedValue = Array.isArray(attr[attrName]) ? attr[attrName] : [attr[attrName]];
attrCombinedValue.forEach(function (attrValue) {
attrKeyValues.push(attrName + keyDelimiter + attrValue);
});
};
for (var _iterator = Object.keys(attr)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
_loop();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return attrKeyValues.join(delimiter);
}
return attrKeyValues.join(delimiter);
}

@@ -1,18 +0,12 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
class: {
delimiter: /\s+/,
glue: ' '
},
style: {
delimiter: /\s*;\s*/,
keyDelimiter: /\s*:\s*/,
glue: '; ',
keyGlue: ': '
}
};
export default {
class: {
delimiter: /\s+/,
glue: ' '
},
style: {
delimiter: /\s*;\s*/,
keyDelimiter: /\s*:\s*/,
glue: '; ',
keyGlue: ': '
}
};
{
"name": "posthtml-attrs-parser",
"version": "0.1.1",
"description": "PostHTML helper that gives a better API to work with tag's attrs",
"main": "index.js",
"version": "1.0.0",
"description": "PostHTML helper that provides a better API to work with tag attributes.",
"main": "lib/index.js",
"type": "module",
"files": [
"lib"
],
"author": "Kirill Maltsev <maltsevkirill@gmail.com>",
"license": "MIT",
"scripts": {
"compile": "rm -f lib/*.js && node_modules/.bin/babel -d lib/ lib/",
"lint": "node_modules/.bin/eslint *.js lib/*.es6 test/",
"pretest": "npm run lint && npm run compile",
"test": "node_modules/.bin/_mocha --compilers js:babel-core/register",
"prepublish": "npm run compile"
"dev": "vitest",
"release": "np",
"lint": "eslint lib/*.js",
"pretest": "npm run lint",
"test": "vitest run --coverage"
},

@@ -19,31 +23,22 @@ "keywords": [

"html",
"postproccessor",
"parser"
"post-processor",
"parser",
"attributes"
],
"babel": {
"presets": [
"es2015"
]
"devDependencies": {
"@vitest/coverage-v8": "^1.2.1",
"eslint": "^8.56.0",
"np": "^9.2.0",
"posthtml": "^0.16.6",
"vitest": "^1.2.1"
},
"dependencies": {
"object-assign": "^4.0.1"
"engines": {
"node": ">=16.0.0"
},
"devDependencies": {
"babel-cli": "^6.3.15",
"babel-core": "^6.3.15",
"babel-eslint": "^4.1.6",
"babel-preset-es2015": "^6.3.13",
"eslint": "^1.10.3",
"expect": "^1.13.0",
"mocha": "^2.3.4",
"posthtml": "^0.8.0"
},
"repository": {
"type": "git",
"url": "git://github.com/maltsev/posthtml-attrs-parser.git"
"url": "https://github.com/posthtml/posthtml-attrs-parser.git"
},
"bugs": {
"url": "https://github.com/maltsev/posthtml-attrs-parser/issues"
},
"homepage": "https://github.com/maltsev/posthtml-attrs-parser"
"bugs": "https://github.com/posthtml/posthtml-attrs-parser/issues",
"homepage": "https://github.com/posthtml/posthtml-attrs-parser"
}

@@ -1,28 +0,45 @@

# PostHTML Attrs Parser
[![npm version](https://badge.fury.io/js/posthtml-attrs-parser.svg)](http://badge.fury.io/js/posthtml-attrs-parser)
[![Build Status](https://travis-ci.org/maltsev/posthtml-attrs-parser.svg?branch=master)](https://travis-ci.org/maltsev/posthtml-attrs-parser)
<div align="center">
<img width="150" height="150" alt="PostHTML" src="https://posthtml.github.io/posthtml/logo.svg">
<h1>posthtml-attrs-parser</h1>
<p>PostHTML plugin for parsing HTML attributes</p>
[PostHTML](https://github.com/posthtml/posthtml) helper that gives a better API to work with tag's attrs.
[![Version][npm-version-shield]][npm]
[![Build][github-ci-shield]][github-ci]
[![License][license-shield]][license]
[![Downloads][npm-stats-shield]][npm-stats]
</div>
[npm]: https://www.npmjs.com/package/posthtml-attrs-parser
[npm-version-shield]: https://img.shields.io/npm/v/posthtml-attrs-parser.svg
[npm-stats]: http://npm-stat.com/charts.html?package=posthtml-attrs-parser
[npm-stats-shield]: https://img.shields.io/npm/dt/posthtml-attrs-parser.svg
[github-ci]: https://github.com/posthtml/posthtml-attrs-parser/actions/workflows/nodejs.yml
[github-ci-shield]: https://github.com/posthtml/posthtml-attrs-parser/actions/workflows/nodejs.yml/badge.svg
[license]: ./license
[license-shield]: https://img.shields.io/npm/l/posthtml-attrs-parser.svg
A [PostHTML](https://github.com/posthtml/posthtml) helper plugin that provides a better API for working with tag attributes.
This plugin is ESM-only.
## Usage
```js
var posthtml = require('posthtml'),
parseAttrs = require('posthtml-attrs-parser');
import posthtml from 'posthtml';
import parseAttrs from 'posthtml-attrs-parser';
posthtml()
.use(function (tree) {
var div = tree[0],
attrs = parseAttrs(div.attrs);
.use(function (tree) {
const div = tree[0];
const attrs = parseAttrs(div.attrs);
attrs.style['font-size'] = '15px';
attrs.class.push('title-sub');
attrs.style['font-size'] = '15px';
attrs.class.push('title-sub');
// Compose attrs back to PostHTML-compatible format
div.attrs = attrs.compose();
})
.process('<div class="title" style="font-size: 14px">Hello!</div>')
.then(function (result) {
console.log(result.html);
});
// Compose attributes back to PostHTML-compatible format
div.attrs = attrs.compose();
})
.process('<div class="title" style="font-size: 14px">Hello!</div>')
.then(function (result) {
console.log(result.html);
});

@@ -32,20 +49,23 @@ // <div class="title title-sub" style="font-size: 15px">Hello!</div>

## Attributes
Only `style` and `class` attributes are parsed by default (as object and array, respectively).
For other attributes the parsing rules should be specified (see "Custom parsing rule" below).
Only `style` and `class` attributes are parsed by default (as object and array, respectively). For other attributes, the parsing rules should be specified (see [Custom parsing rule](#custom-parsing-rule) below).
### Default attributes
#### `style`
```html
<div style="color: red; font-size: 14px; color: blue"></div>
```
```js
// <div style="color: red; font-size: 14px; color: blue"></div>
var attrs = parseAttrs(div.attrs);
const attrs = parseAttrs(div.attrs);
console.log(attrs.style);
/*
{
// If there is several properties with the same name,
// then the values are packed in array
'color': ['red', 'blue'],
'font-size': '14px'
// If there are several properties with the same name,
// the values are packed in array
'color': ['red', 'blue'],
'font-size': '14px'
}

@@ -55,7 +75,10 @@ */

#### `class`
#### `class`
```html
<div class="title title-sub"></div>
```
```js
// <div class="title title-sub"></div>
var attrs = parseAttrs(div.attrs);
const attrs = parseAttrs(div.attrs);
console.log(attrs.class);

@@ -65,19 +88,23 @@ // ['title', 'title-sub']

### Custom parsing rule
You can also define the parsing rule for other attributes.
You may also define the parsing rule for other attributes.
#### Array-like attribute
```html
<div data-ids="1 2 4 5 6"></div>
```
```js
// <div data-ids="1 2 4 5 6"></div>
var attrs = parseAttrs(div.attrs, {
rules: {
'data-ids': {
delimiter: /\s+/,
// Optional parameter for stringifying attribute's values
// If not set, glue = delimiter
glue: ' '
}
}
const attrs = parseAttrs(div.attrs, {
rules: {
'data-ids': {
delimiter: /\s+/,
// Optional parameter for stringifying attribute's values
// If not set, glue = delimiter
glue: ' '
}
}
});
console.log(attrs['data-ids']);

@@ -90,23 +117,25 @@ // ['1', '2', '4', '5', '6']

#### Object-like attribute
#### Object-like attribute
```html
<div data-config="TEST=1;ENV=debug;PATH=."></div>
```
```js
// <div data-config="TEST=1;ENV=debug;PATH=."></div>
var attrs = parseAttrs(div.attrs, {
rules: {
'data-config': {
// Delimiter for key-value pairs
delimiter: ';',
// Delimiter for a key-value
keyDelimiter: '=',
const attrs = parseAttrs(div.attrs, {
rules: {
'data-config': {
// Delimiter for key-value pairs
delimiter: ';',
// Delimiter for a key-value
keyDelimiter: '=',
// Optional parameter for stringifying key-value pairs
// If not set, keyGlue = keyDelimiter
glue: '; ',
// Optional parameter for stringifying a key-value
// If not set, glue = delimiter
keyGlue: ' = '
}
}
});
// Optional parameter for stringifying key-value pairs
// If not set, keyGlue = keyDelimiter
glue: '; ',
// Optional parameter for stringifying a key-value
// If not set, glue = delimiter
keyGlue: ' = '
}
}
});
console.log(attrs['data-config']);

@@ -113,0 +142,0 @@ // {TEST: '1', ENV: 'debug', PATH: '.'}

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc