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
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
Extends String
Token interface
Parameters
group
The group it matched.
Type: string
value
The value of the match.
index
The index position of the match.
source
The input string.
Type: RegExpMatchArrayLike
Contribute
All contributions are welcome!
License
MIT © 2021 stagas