Can I rely on `pregQuote` in `string-utils-common.js` escaping regular expressions?

Summary

I want to be able to escape strings for usage in regular expressions. The code to do this (taken from the escape-string-regex library) is very short:

escape-string-regex/index.js
// From escape-string-regex:

// https://github.com/sindresorhus/escape-string-regexp/blob/main/index.js
export default function escapeStringRegexp(string) {
	if (typeof string !== 'string') {
		throw new TypeError('Expected a string');
	}

	// Escape characters with special meaning either inside or outside character sets.
	// Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
	return string
		.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
		.replace(/-/g, '\\x2d');
}
.

Joplin already has a function that seems to escape strings for use in regular expressions:

Questions

  • Can I rely on this function escaping regular expressions in the future? (Is that its intended usage, or is it more specialized?)
  • Currently string-utils-common.js lacks type definitions. To use its contents in a PR, I would have to add a .d.ts file or migrate string-utils-common.js to TypeScript.
    • I see a one PR at a time guideline. Would it be appropriate to migrate string-utils-common.js to TypeScript and document pregQuote in a second PR?

Yes pregQuote should be used for this as it's already been indirectly (and maybe directly) tested in various places.

For string-utils-common.js you don't have to add .d.ts, you can import it using require(). It will be untyped but that's fine for now. This is old code that hasn't been updated yet.

As for the one PR limit it only applies in the first phase of GSoC, so feel free to create more if you need to.

1 Like

I'm importing from a bundled JS file. At least with its current configuration, rollup isn't recognizing require(...) imports. As such, I'll need to refactor string-utils-common.js before using it (or re-configure rollup).

Hmm, it's JS, how is it possible that it cannot import a JS file? Surely there's some config option to support this?

At this point I'd rather we leave this file as it is. I forgot exactly how it's setup, it's not a good setup, but making that clean would be more work than it's worth.

1 Like