Skip to content

Instantly share code, notes, and snippets.

@Edgar-P-yan
Last active June 29, 2022 19:59
Show Gist options
  • Save Edgar-P-yan/632259948843522aa8038d980a4f066a to your computer and use it in GitHub Desktop.
Save Edgar-P-yan/632259948843522aa8038d980a4f066a to your computer and use it in GitHub Desktop.
[Node.js] Escape function for PostgreSQL LIKE/ILIKE operator
/**
* Escapes pattern-characters of LIKE and ILIKE operators.
*
* @example
* query('SELECT * FROM articles WHERE title LIKE $1', [ '%' + escapePostgresLikeOperator(searchString) + '%' ])
*
* @param input {string} string to escape
*
* @returns {string} the string to use in LIKE/ILIKE clause
*/
export function escapePostgresLikeOperator(input) {
return input.replace(/\\/g, '\\\\').replace(/\_/g, '\\_').replace(/%/g, '\\%');
}
/**
* Escapes pattern-characters of LIKE and ILIKE operators.
*
* @example
* query('SELECT * FROM articles WHERE title LIKE $1', [ '%' + escapePostgresLikeOperator(searchString) + '%' ])
*
* @param input {string} string to escape
*
* @returns {string} the string to use in LIKE/ILIKE clause
*/
export function escapePostgresLikeOperator(input: string): string {
return input.replace(/\\/g, '\\\\').replace(/\_/g, '\\_').replace(/%/g, '\\%');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment