Skip to content

Instantly share code, notes, and snippets.

@vrutberg
Created September 22, 2009 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrutberg/190935 to your computer and use it in GitHub Desktop.
Save vrutberg/190935 to your computer and use it in GitHub Desktop.
JavaScript implementation of the NotesName class
function NotesName(p) {
var name = p;
// regular expressions that we use to extract information
var Regexp = {
abbreviated: /(?:CN|OU|O|C)=/gi,
isName: /CN=.+(?:\/OU=.+)*\/O=.+(?:\/C=.+)?/i,
common: /CN=([\w\s]*)\//i,
given: /^(\w+)\s/,
surname: /\s(\w+)$/,
organization: /\/O=([\w\s]*)\//i,
country: /\/C=([\w\s]*)/i
};
if(!Regexp.isName.test(name)) {
// TODO: Perhaps we need some proper error handling here instead of returning null?
return null;
}
// tries to extract a piece of information, returns null on failure
function extract(subject, regexp) {
if(subject === null || subject === undefined || regexp === null || regexp === undefined) {
return null;
}
var matches = subject.match(regexp, "i");
if(matches !== null && matches !== undefined && matches.length >= 2) {
return matches[1];
}
return null;
}
return {
getAbbreviated: function() {
return name.replace(Regexp.abbreviated, '');
},
getHierarchical: function() {
return name;
},
getCommon: function() {
return extract(name, Regexp.common);
},
getGiven: function() {
return extract(this.getCommon(), Regexp.given);
},
getSurname: function() {
return extract(this.getCommon(), Regexp.surname);
},
getOrganization: function() {
return extract(name, Regexp.organization);
},
getCountry: function() {
return extract(name, Regexp.country);
},
// use the other methods if possible, this one is about 1.8x slower
getPiece: function(piece) {
return extract(name, piece+"=([\\w\\s]*)");
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment