Last active
June 29, 2022 19:59
-
-
Save Edgar-P-yan/632259948843522aa8038d980a4f066a to your computer and use it in GitHub Desktop.
[Node.js] Escape function for PostgreSQL LIKE/ILIKE operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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, '\\%'); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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