Danielo515 has introduced a useful widget (context.js*) which looks for a word inside a tiddler and shows the result with the searched word highlighted with some of its context.
It extract before characters before the word and after afterwards. (before and after are parameters).
I would rather have the widget to extract the context before up to the beginning of the line containing the word instead of a fixed number of characters.
I think that this should be possible with a modification in the following regexp.
var regString = "(\\w+[\\s\\S]{0,#before#})?(#term#)([\\s\\S]{0,#after#}\\w+)?";
However, I was not able to have something work (trying several things such as (\\n[\\s\\S]*)?(#term#)([\\s\\S]{0,#after#}\\w+)?";)
Have you tried ^.*#term#.{0,#after#} ? Don’t forget the multiline flag (m) for the regex too.
In the infinite wisdom of GigantiCorps, I can’t see the tiddlyspot site with that plugin, so I don’t know exactly how this is built. But in pure JS, I might do something like this:
const makeContextRegex = (term, after) =>
new RegExp(`^.*${term}.{0,${after}}`, `gm`)
// you might want `gim` instead for case-insensitive
const str =
`We won't get fooled again!
Nothing to see here but barbarian bazookas.
Come, Watson! The Game is Afoot!
I took him for a kind of buffoon. Now I see he is a devil.
(this space intentionally left blank)
Wait, but it wasn't actually blank!
A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines
`
const regex = makeContextRegex('foo', 20)
str.match(regex) //=>
// [
// "We won't get fooled again!",
// "Come, Watson! The Game is Afoot!",
// "I took him for a kind of buffoon. Now I see he is a",
// "A foolish consistency is "
// ]