skip to Main Content

So here’s an example string:
CN=John Doe,OU=IT,OU=Management Support Services,OU=Divisions,OU=Accounts,DC=company,DC=com

I only need to get the first name out of this string. In this case the name being John Doe. I can’t hard code a number of characters in as the names there can vary in length.

Basically I need to select the string after CN= and then end it at the first comma.

The first number can always be 3 characters since the CN= is always there. Is there anyway for me to use the first comma as the end point?

I’m trying to do something like this.

let name = reports[i].mgrdn;
let result = name.split(3, ",")

Any help would be appreciated. Even just a suggestion about what method to use.

4

Answers


  1. You can do this by using the indexOf method and then slice

    function extractFirstName(str) {
      let startIndex = str.indexOf("CN=") + 3;
      let endIndex = str.indexOf(",", startIndex);
      if (startIndex < 0 || endIndex < 0) {
        return null;
      }
      let firstName = str.slice(startIndex, endIndex);
      return firstName;
    }
    
    // Example
    let name = "CN=John Doe,OU=IT,OU=Management Support Services,OU=Divisions,OU=Accounts,DC=company,DC=com";
    let firstName = extractFirstName(name);
    console.log(firstName);
    Login or Signup to reply.
  2. This will give you what you need.

     result = name.split(',')[0].split('=')[1];
    

    Of course you should probably validate the format is what is expected too.

    As @freedomn-m says…

    Step-by-step:

    • take name, split on comma, take first entry (all text before first comma),
    • split that on = and take all text after the equal (from the text before the first comma)
    Login or Signup to reply.
  3. If you want to use regex:

    let regex = new RegExp("=(.*?),");
    let input = "CN=John Doe,OU=IT,OU=Management Support Services,OU=Divisions,OU=Accounts,DC=company,DC=com"
    
    let [_, name] = input.match(regex)
    
    console.log("Name:", name);

    https://regex101.com/r/i4p0Ks/1

    Login or Signup to reply.
  4. If you need to get more than just the first you can convert it in to query params.

    const str = 'CN=John Doe,OU=IT,OU=Management Support Services,OU=Divisions,OU=Accounts,DC=company,DC=com';
    const searchParams = new URLSearchParams(str.replace(/,/g,"&"));
    console.log('CN', searchParams.get("CN"));
    console.log('OU', searchParams.getAll("OU"));
    console.log('DC', searchParams.getAll("DC"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search