string wrapper that keeps track of its original location in a file
import { Segment } from 'parse-segment'
const data = new Segment({
value: `no matter how you slice
this, it still knows where
it came from
`,
source: 'foo.txt',
})
console.log(data.substring(32, 39).trim().underlineInContext())
Output:
this, it still knows where
^^^^^
Represents a string value plus information about its location in a source file.
Segment
has the same methods as JS strings, but its methods instances of
Segment
that retain their location information:
charAt
charCodeAt
codePointAt
endsWith
indexOf
includes
lastIndexOf
localeCompare
match
search
slice
startsWith
substring
split
trimStart
trimEnd
trim
However, methods that change the text beyond slicing it up, like toUpperCase
, replace
, etc. are excluded.
The string text
Where the text came from, for example, a file path or URL
The line on which the segment begins, starting with 0.
The column on which the segment begins, starting with 0.
The string text
Where the text came from, for example, a file path or URL
The line on which the segment begins, starting with 0.
The column on which the segment begins, starting with 0.
The line on which the segment ends, starting with 0.
The column on which the segment ends, starting with 0.
The length of the text
Returns the lines of text on which this segment occurs, interleaved with lines containing ^^^^ underlining the portion the segment represents.
A handy class for parsing text as a Segment
and throwing contextual errors if necessary.
Creates a parser on segment
starting at index
0
.
The Segment
being parsed.
The current parse position within segment
.
Moves index
past the next occurrence of rx
. Returns true
if anything was
skipped, false
otherwise.
Checks if segment
has a match for rx
at the current index
. If so, returns it and moves index
past it.
If not, throws a SegmentParseError
with messageIfMissing
.
Moves the index
past the next match for rx
, and returns the sub-Segment
from the starting index
up to the match. For example, .nextDelimited(/\r\n?|\n/mg)
will return the rest of the current line and move to the next line. If
messageIfMissing
is given, will throw a SegmentParseError
if no match for rx
is found beyond the current index
. Otherwise, it will return the sub-Segment
from the current index
all the way to the end.
Checks if segment
contains str
at the current index
. If so, moves index
past it.
If not, throws a SegmentParseError
with messageIfMissing
.
Same as .expect
, but performs a case-insensitive comparison.
Returns a string containing only the character at the current index
.
Returns true
if the current index
is at the end of the segment
, false
otherwise.
Returns true
if the current index
is at the end of a line, false
otherwise.