Skip to main content

RFC 2254 (The String Representation of LDAP Search Filters) escaping of filter strings.

// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

/**
 * RFC 2254 Escaping of filter strings
 *
 * Raw                     Escaped
 * (o=Parens (R Us))       (o=Parens \28R Us\29)
 * (cn=star*)              (cn=star\2A)
 * (filename=C:\MyFile)    (filename=C:\5cMyFile)
 *
 * Use substr_filter to avoid having * ecsaped.
 *
 * @author [Austin King](https://github.com/ozten)
 */
exports.escape = function (inp) {
    if (typeof inp === "string") {
        let esc = "";
        for (let i = 0; i < inp.length; i++) {
            switch (inp[i]) {
                case "*":
                    esc += "\\2a";
                    break;
                case "(":
                    esc += "\\28";
                    break;
                case ")":
                    esc += "\\29";
                    break;
                case "\\":
                    esc += "\\5c";
                    break;
                case "\0":
                    esc += "\\00";
                    break;
                default:
                    esc += inp[i];
                    break;
            }
        }
        return esc;
    } else {
        return inp;
    }
};