Skip to content

Instantly share code, notes, and snippets.

@Kirill89
Last active January 11, 2018 09:03
Show Gist options
  • Save Kirill89/0c677ec9a09ecc48320ec29b0d8bcf4d to your computer and use it in GitHub Desktop.
Save Kirill89/0c677ec9a09ecc48320ec29b0d8bcf4d to your computer and use it in GitHub Desktop.
Escape MySQL LIKE % and _ characters in JavaScript
// https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html#operator_like
const escapeLike = str => str.replace(/\\/g, '\\\\').replace(/([%_])/g, '\\$1');
console.log(escapeLike('%test_') === '\\%test\\_');
console.log(escapeLike('\\%test\\_') === '\\\\\\%test\\\\\\_');
console.log(escapeLike('\\\\%test\\\\_') === '\\\\\\\\\\%test\\\\\\\\\\_');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment