Parse the String

maryc
Tera Contributor

Hi,

I have a String in LDAP format and I want to get only the name from it. How do I parse this String with JS ?

CN=Bill\,Hamilton,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com

I want to extract the name Bill Hamilton from this entire String

Thanks

1 ACCEPTED SOLUTION

justin_drysdale
Mega Guru

Hi Mary,



String parsing comes up so often in Service Now that I constructed a nifty scraping function.   It isn't the fastest, but it is the coolest!   I think it is easier to understand than using the split method.   Splitting, and then splitting again, and maybe even splitting again on top of that gets messy.



var ldap_path = 'CN=Bill\,Hamilton,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com';


var first_name = grabContent(ldap_path, 'CN=', '\,');// Bill


var last_name = grabContent(ldap_path, '\,', ',OU=');// Hamilton




gs.print("frist name: " + first_name + "\nlast_name: " + last_name);




function   grabContent(str, start, end) {  


    var startLen = start.length;  


    var s = str.indexOf(start);  


    var e = str.indexOf(end);  


    var scrape = str.substring(s+startLen, e);  


    return scrape;  


}



To use the grabContent function, pass in the string you want to parse as the first parameter, the start of the parse as the 2nd parameter, and end of the parse as the final parameter.     Please let me know if you have any questions.


View solution in original post

7 REPLIES 7

sonali_panda
Giga Expert

Hi Mary,


Try this


var ag = CN=Bill\,Hamilton,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com


var testArray = ag.split('\,');


var curValue = (testArray[2] +" " + testArray[3])




Thanks


Sonali


Mihir Mohanta
Kilo Sage

Hi Mary,



Please try below script:



var str = "CN=Bill\,Hamilton,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com"; // Write syntax to get the source   in place of the string


var rep = str.replace('\,',' ');


var fullname= rep.split(",")[0]; // fullname variable stores   the Full name from the source string.



Please mark it as Helpful/Correct according to its impact.



Thanks,


Mihir


Mihir,



I get CN= Bill Hamilton. I think I need to do one more split based on "=" to get the full name


Hi Mary,


You are very close to result. Please try the modified script below:



var str = "CN=Bill\,Hamilton,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com";


var spt = str.split("=")[1];


var rep = spt.replace('\,',' ');


var fullname= rep.split(",")[0]; // fullname variable stores   the Full name from the source string.



Please mark it as Helpful/Correct according to its impact



Thanks,


Mihir