[Solved] javascript code for converting distinguished name into canonical name


The easiest way is to replace \, with some string that is guaranteed to not appear anywhere else in the string. That way, it is ignored when you Split(",").

Then replace it with , when you return the result. In this case I use "{comma}":

private static string ExtractCN(string dn)
{
    dn = dn.Replace("\\,", "{comma}");
    string[] parts = dn.Split(new char[] { ',' });

    for (int i = 0; i < parts.Length; i++)
    {
        var p = parts[i];
        var elems = p.Split(new char[] { '=' });
        var t = elems[0].Trim().ToUpper();
        var v = elems[1].Trim();
        if (t == "CN")
        {
            return v.Replace("{comma}", ",");
        }
    }
    return null;
}

That answers your immediate question, but you still have some work to do since this only returns "Peterson,Misha", not the full canonical name.

You could theoretically get better performance by not using Split and walking each character in the string yourself… but I doubt it would make a noticeable difference.

Your code example looks more like C# than JavaScript. If you are indeed using C#, you could just pull the value of the canonicalName attribute directly from Active Directory:

var de = new DirectoryEntry($"LDAP://{dn}");
de.RefreshCache(new [] { "canonicalName" });
var canonicalName = (string) de.Properties["canonicalName"].Value;

1

solved javascript code for converting distinguished name into canonical name