We invented the term, but it's just a fancy way to describe arrays of "from" — "to" string index ranges:
[10, 15, "replacement"],
[3, 7] means delete characters from index
[10, 15, "replacement"] means replace characters from index
A case of no ranges is marked by
null (but if you pass an empty array, it will work too).
Same indexes as in
Ranges gives us the flexibility to process strings. For example, detergent taps different packages, one to strip HTML, another to remove widow words and so on — they all report ranges. They all operate on the same source string, not on the source, mutated by the previous operation.
That's a different approach from the old way, mutating string over and over using regexes.
§ Range Libraries
It takes the source string and the amendments described by Ranges and produces a new string.
ranges-push also checks the types so it acts like a safeguard.
If, after sorting, any two ranges in the vicinity have the same edge value (like
2 below), merge them.
It sorts the ranges.
It crops the ranges, ensuring no range from an array goes beyond a given index.
Takes a string, matches the given regex on it and returns ranges which would do the same thing.
String.prototype.match(), a no-results case will yield
null (which ranges-merge and others would gladly accept).
This is a wrapper on top of market-leading HTML entity decoder he.js
decode() which returns ranges instead of string.
We tested the hell out of the code, directly and up-the-dependency-stream but as a cherry on top, all he.js unit tests were ported to
node-tap and do pass.
Tells, is a given natural number index within any of the ranges. It's a wrapper on top of
It iterates all characters in a string, as if given ranges were already applied.
Sometimes certain operations on a string aren't really composable — sometimes we want to traverse the string as if ranges were applied, as if we already had the final result.
Processes the string outside the given ranges. Each "gap" in the string between ranges will be fed into callback you supply — same like in
This program makes the life easier because if you did it manually, you'd have to invert ranges and loop over each inverted chunk. Finally, you'd have to write unit tests of all that.
magic-string by Rich Harris, the Rollup creator.
It is an all-in-one program to perform operations on strings in a controllable manner. It's oriented at operations on code, and its produced sourcemaps are aimed at browsers.
Range libraries are best used for when you want to:
- transfer string amendment instructions between programs
- gather string amendment instructions and discard some, conditionally, or tweak them
- when string processing is complex
magic-string is best used in programs similar to Rollup: you process code and generate sourcemaps for browsers.