§ Quick Take

import { strict as assert } from "assert";
import raReg from "ranges-regex";

const oldString = `The quick brown fox jumps over the lazy dog.`;
const result = raReg(/the/gi, oldString);

// all regex matches, but in Ranges notation (see codsen.com/ranges/):
assert.deepEqual(result, [
  [0, 3],
  [31, 34],

// if you slice the ranges, you'll get original regex caught values:
  result.map(([from, to]) =>
    oldString.slice(from, to)
  ["The", "the"]

§ Purpose

Takes a string, matches the given regex on it and returns ranges which would do the same thing.

Similarly to String.prototype.match(), a no-results case will yield null (which ranges-merge and others would gladly accept).


raReg(regexp, str, [replacement])

In other words, it's a function which takes three input arguments, third one is optional (marked with square brackets).

Input argumentTypeObligatory?Description
regexpRegular expressionyesProvide the regexp to apply onto a string
strStringyesProvide a string upon which to match the regex
replacementString or nullnoIf you want to add a third argument on every of the finding's third argument values, put it here.

Output: array of zero or more arrays (so-called ranges) where each consists of two or more natural number (or zero) indexes OR null.

This package does not mutate its inputs.

If the input arguments' types are incorrect or absent, library will throw an error.

§ Examples

Nothing to find:

// nothing to find:
console.log(raReg(/yyy/g, "zzzzzzzz"));
// => null

// stick `null` to add onto every of the findings:
const res = raReg(/def/g, "abcdefghij_abcdefghij", null);
console.log(JSON.stringify(res, null, 4));
// => [[3, 6, null], [14, 17, null]]

Notice, you can use all the features of regexes: global, case insensitive flags and so on.

PS. Be careful not to signify the intention to omit the third argument by setting it to null. The null is a valid value in ranges ecosystem opens in a new tab and it is used in ranges to "kill off" any present insertion values. For example, you merge two ranges and one says "add this" (in a form of third argument) and second says, disregard all that content to add, here's null to defuse them for good.

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 ranges-invert 2.1.49
Invert string index ranges
📦 ranges-sort 3.13.3
Sort string index ranges
📦 ranges-push 3.7.22
Gather string index ranges
📦 ranges-process-outside 2.2.35
Iterate string considering ranges, as if they were already applied
📦 ranges-crop 2.1.3
Crop array of ranges when they go beyond the reference string's length
📦 ranges-merge 5.0.3
Merge and sort string index ranges
📦 ranges-is-index-within 1.15.2
Checks if index is within any of the given string index ranges