match-to-token

transform a RegExp named group match to a more useful object

Usage no npm install needed!

<script type="module">
  import matchToToken from 'https://cdn.skypack.dev/match-to-token';
</script>

README

match-to-token

transform a RegExp named group match to a more useful object

🔧 Install · 🧩 Example · 📜 API docs · 🔥 Releases · 💪🏼 Contribute · 🖐️ Help


Install

$ npm i match-to-token

What it does

It picks up the first matching named group from a RegExp string.match() or string.matchAll() result and creates a Token object with that value.

Why

Extracting the name of the group that was captured from a match result isn't trivial and can be done incorrectly which can lead to errors. This module is tested and will (hopefully) not fail.

Example

import { matchToToken } from 'match-to-token'

const match = 'foo'.match(/(?<bar>[o])/)!
const token = matchToToken(match)
console.log(token)
// => { group: 'bar', value: 'o', index: 1 }

const matches = 'foo'.matchAll(/(?<bar>[o])/g)
for (const match of matches) {
  const token = matchToToken(match)
  console.log(token)
  // => { group: 'bar', value: 'o', index: 1 }
  // => { group: 'bar', value: 'o', index: 2 }
}

API

Table of Contents

matchToToken

src/index.ts:20-28

Convert a match object from string.match() or string.matchAll() with a named group RegExp such as /(?<group>[a-z])/ to a more useful Token object.

Parameters

  • match (RegExpMatchArray | null) The match object

Returns (MatchToken | null)

Token

src/token.ts:6-44

Extends String

Token interface

Parameters

group

src/token.ts:13-13

The group it matched.

Type: string

value

src/token.ts:17-19

The value of the match.

index

src/token.ts:23-25

The index position of the match.

source

src/token.ts:29-29

The input string.

Type: RegExpMatchArrayLike

Contribute

Fork or edit and submit a PR.

All contributions are welcome!

License

MIT © 2021 stagas