Last active
January 11, 2018 09:03
-
-
Save Kirill89/0c677ec9a09ecc48320ec29b0d8bcf4d to your computer and use it in GitHub Desktop.
Escape MySQL LIKE % and _ characters in JavaScript
This file contains 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
// 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