Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Created January 16, 2026 13:29
Show Gist options
  • Select an option

  • Save coderofsalvation/f85678d8a650b7c17a66737cedf8ed8c to your computer and use it in GitHub Desktop.

Select an option

Save coderofsalvation/f85678d8a650b7c17a66737cedf8ed8c to your computer and use it in GitHub Desktop.
naive URI text fragment javascript function
textFragment("foo bar hello spatial world flop flap", '#:~:text=hello,world')
// hello spatial world
textFragment("foo bar hello spatial world flop flap", '#:~:text=hello spatial,flap')
// hello spatial world flop flap
// naive implementation: this only supports the main usecase: begin/end
var textFragment = function(text, fragment) {
if (!fragment.match(/^#:~:text=/)) return text;
fragment = fragment.replace(/^#:~:text=/, ''); // remove prefix
const parts = fragment.split(',');
const start = decodeURIComponent(parts[0] || '');
const stop = decodeURIComponent(parts[1] || '');
// Build regex dynamically, escape special characters
const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(
escapeRegExp(start) + '(.*?)' + escapeRegExp(stop),
's' // 's' flag makes '.' match newline too
);
const match = text.match(regex);
if ( text.match(regex) ) return match[0]
if (start) {
const startIndex = text.indexOf(start);
if (startIndex >= 0) return text.slice(startIndex);
}
return text; // fallback
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment