Package Exports
- string-match-left-right
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (string-match-left-right) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
string-match-left-right
Do substrings match what's on the left or right of the given index?
Table of Contents
Install
npm i string-match-left-right
// CommonJS way:
const { matchLeftIncl, matchRightIncl, matchLeft, matchRight } = require('string-match-left-right')
// ES Modules way:
import { matchLeftIncl, matchRightIncl, matchLeft, matchRight } from 'string-match-left-right'
Here's what you'll get:
Type | Key in package.json |
Path | Size |
---|---|---|---|
Main export - CommonJS version, transpiled down to Node v.4 spec, contains require and module.exports |
main |
dist/string-match-left-right.cjs.js |
8 KB |
ES module build that Webpack/Rollup understands. Untranspiled ES6 code with import /export . |
module |
dist/string-match-left-right.esm.js |
7 KB |
UMD build for browsers, transpiled, minified, containing iife 's and has all dependencies baked-in |
browser |
dist/string-match-left-right.umd.js |
33 KB |
The API
There are four methods; all have the same API's:
matchLeftIncl
— at least one of given substrings has to match what's on the left and including character at the given indexmatchRightIncl
— at least one of given substrings has to match what's on the right and including character at the given indexmatchLeft
— at least one of given substrings has to match what's on the left of the given indexmatchRight
— at least one of given substrings has to match what's on the right of the given index
Input argument | Type | Obligatory? | Description |
---|---|---|---|
str |
String | yes | Source string to work on |
position |
Natural number incl. zero | yes | Starting index. Can be zero. Otherwise, a natural number. |
whatToMatch |
String or array of strings | yes | What should we look for on the particular side, left or right. If array is given, at one or more matches will yield in result true |
opts |
Plain object | no | The Optional Options Object. See below. |
Optional Options Object's API:
options object's key |
Type | Obligatory? | Default | Description |
---|---|---|---|---|
{ | ||||
i |
Boolean | no | false |
If false , it's case sensitive. If true , it's insensitive. |
cb |
Function | no | undefined |
If you feed a function to this key, that function will be called with the remainder of the string. Which side, it depends on which side method (left side for matchLeft and matchLeftIncl and others for right accordingly) is being called. The result of this callback will be joined using "AND" logical operator to calculate the final result. I use cb mainly to check for whitespace. |
trimBeforeMatching |
Boolean | no | false |
If set to true , there can be whitespace before what's being checked starts. Basically, this means, substring can begin (when using right side methods) or end (when using left side methods) with a whitespace. |
trimCharsBeforeMatching |
String or Array of zero or more strings | no | [] |
If set to true , similarly like trimBeforeMatching will remove whitespace, this will remove any characters you provide in an array. For example, useful when checking for tag names to the right of < , with or without closing slash, <div or </div . |
} |
Here it is with defaults, in one place, ready for copying:
{
i: false,
cb: undefined,
trimBeforeMatching: false,
trimCharsBeforeMatching: []
}
The Optional Options Object is sanitized by check-types-mini which will throw
if you set options' keys to wrong types or add unrecognized keys.
// K E Y
// -----
// test string with character indexes to help you count:
//
// test string: a b c d e f g h i
// indexes of letters above: 0 1 2 3 4 5 6 7 8
//
// a is #0, b is #1 and so on. Look the digit under letter above.
//
// that is, c is number (term "number" further abbreviated as hash character "#") 2 or i is #8.
//
// we'll be using the same string "abcdefghi" below:
const { matchLeftIncl, matchRightIncl, matchLeft, matchRight } = require('string-match-left-right')
let res1 = matchLeftIncl('abcdefghi', 3, ['bcd'])
// 3rd character is "d" because indexes start from zero.
// We're checking the string to the left of it, "bcd", inclusive of current character ("d").
// This means, "bcd" has to end with existing character and the other chars to the left
// must match exactly:
console.log(`res1 = ${res1}`)
// => res1 = true
let res2 = matchLeft('abcdefghi', 3, ['ab', `zz`])
// neither "ab" nor "zz" are to the left of 3rd index, "d":
console.log(`res2 = ${res2}`)
// => res2 = false
let res3 = matchRightIncl('abcdefghi', 3, ['def', `zzz`])
// "def" is to the right of 3rd index (including it), "d":
console.log(`res3 = ${res3}`)
// => res3 = true
let res4 = matchRight('abcdefghi', 3, ['ef', `zz`])
// One of values, "ef" is exactly to the right of 3rd index, "d":
console.log(`res4 = ${res4}`)
// => res4 = true
opts.cb
Often you need not only to match what's on the left/right of the given index within string, but also to perform checks on what's outside.
For example, if you are traversing the string and want to match the class
attribute, you traverse backwards, "catch" equals character =
, then check, what's on the left of it using method matchLeft
. That's not enough, because you also need to check, is the next character outside it is a space, or in algorithm terms, "trims to length zero", that is (trim(char).length === 0)
. How do you apply this check?
Using opts.cb
callbacks ("cb" stands for CallBack):
const { matchLeftIncl, matchRightIncl, matchLeft, matchRight } = require('string-match-left-right')
// imagine you looped the string and wanted to catch where does attribute "class" start
// and end (not to mention to ensure that it's a real attribute, not something ending with this
// string "class").
// You catch "=", an index number 8.
// This library can check, is "class" to the left of it and feed what's to the left of it
// to your supplied callback function, which happens to be a checker "is it a space":
function isSpace(char) {
return (typeof char === 'string') && (char.trim() === '')
}
let res = matchLeft('<a class="something">', 8, 'class', { cb: isSpace })
console.log(`res = ${JSON.stringify(res, null, 4)}`)
// => res = true
The callback function will receive two arguments:
- first argument - the character on the left/right side (depending which side method this is)
- second argment - whole substring that begins or ends with first argument. This might come handy if you want to perform check on more than one character outside of the matched characters.
For example:
const { matchLeftIncl, matchRightIncl, matchLeft, matchRight } = require('string-match-left-right')
function startsWithZ(firstCharacter, wholeSubstring) {
// console.log(`firstCharacter = ${JSON.stringify(firstCharacter, null, 4)}`)
// console.log(`wholeSubstring = ${JSON.stringify(wholeSubstring, null, 4)}`)
return wholeSubstring.startsWith('z')
}
const test01 = matchLeft('<div><b>aaa</b></div>', 5, ['<div>'])
console.log(`test01 = ${JSON.stringify(test01, null, 4)}`)
// => true, // the 5th index is left bracket of <b>. Yes, <div> is on the left.
const test02 = matchLeft('z<div ><b>aaa</b></div>', 7, ['<div>'])
console.log(`test02 = ${JSON.stringify(test02, null, 4)}`)
// => false, // the 7th index is left bracket of <b>. Yes, <div> is on the left.
const test03 = matchLeft('z<div ><b>aaa</b></div>', 7, ['<div'], { trimCharsBeforeMatching: [' >'] })
console.log(`test03 = ${JSON.stringify(test03, null, 4)}`)
// => true, // the 7th index is left bracket of <b>. Yes, <div> is on the left.
const test04 = matchLeft('z<div ><b>aaa</b></div>', 7, ['<div'], { cb: startsWithZ, trimCharsBeforeMatching: [' >'] })
console.log(`test04 = ${JSON.stringify(test04, null, 4)}`)
// => true, // the 7th index is left bracket of <b>. Yes, <div> is on the left.
const test05 = matchLeft('<div ><b>aaa</b></div>', 6, ['<div'], { cb: startsWithZ, trimCharsBeforeMatching: [' >'] }),
console.log(`test05 = ${JSON.stringify(test05, null, 4)}`)
// => false, // deliberately making the second arg of cb to be blank and fail startsWithZ
opts.trimBeforeMatching
For example, string-strip-html is using this library to check, is there a known HTML tag name to the right of the opening bracket character (<
). Like <div
or <img
. Now, we want to allow dirty code cases when there's whitespace after the bracket, like < div
, just in case somebody would sneak in < script
and some browser would "patch it up". In string-strip-html
, we want to be able to detect and strip even <\n\n\nscript>
. That's easy, we set opts.trimBeforeMatching
to true
. When matching is performed, substring on the right of <
, the \n\n\nscript
, is trimmed into script
, then matched.
By the way it's not on by default because such scenarios are rare. Default comparison should be a strict-one.
opts.trimCharsBeforeMatching
For example, string-strip-html will look for opening and closing tags. First it will locate opening bracket <
. Then it will check, is there a known tag name to the right, but trimming any /
's, to account for closing slashes.
Contributing
Hi! 99% of people in the society are passive - consumers. They wait for others to take action, they prefer to blend in. The remaining 1% are proactive citizens who will do something rather than wait. If you are one of that 1%, you're in luck because I am the same and together we can make something happen.
If you want a new feature in this package or you would like to change some of its functionality, raise an issue on this repo. Also, you can email me. Just let it out.
If you tried to use this library but it misbehaves, or you need an advice setting it up, and its readme doesn't make sense, just document it and raise an issue on this repo. Alternatively, you can email me.
If you don't like the code in here and would like to give advice about how something could be done better, please do. Same drill - GitHub issues or email, your choice.
If you would like to add or change some features, just fork it, hack away, and file a pull request. I'll do my best to merge it quickly. Code style is
airbnb-base
, only without semicolons. If you use a good code editor, it will pick up the established ESLint setup.
Licence
MIT License (MIT)
Copyright © 2017 Codsen Ltd, Roy Revelt