Regular Expression help

Michael M1
Giga Expert

I need to extract the user name from an AD attribute.

The string looks something like "CN=Rosana Smith,OU=Employees,..."

I wrote an expression of: var mike = str.match(/\b(\w)+ (\w)+/jg);

This works, except if I run into a name of Rosana Smith-Jones, it will not capture the third name. If I adjust to match against this then it doesn't work for non-hyphen names. Also, some people have 3 names "Billy Rae Cyrus".

My question is, how can I write an expression to capture all characters between (but not including) the CN= and the first comma (,) ?

1 ACCEPTED SOLUTION

Here is how you would get the name out of the string:

var myString = "CN=Rosana Smith,OU=Employees,..";
var myRegexp = /CN=(.*?),/g;
var match = myRegexp.exec(myString);
gs.print(match[1]);

The idea is you want to retrieve the first matching group and not the match itself.  Run it in a Background Script or in  Xplore: Developer Toolkit.

View solution in original post

8 REPLIES 8

Jim Coyne
Kilo Patron

I believe this should do it:

/CN=(.*?),/g

Jim - 

This is always what I thought as well - everything in the parenthesis is what gets extracted, but that is not what is happening.

If I put your suggestion into ServiceNow I get the following output:

Script: CN=Rosana Smith,

Here is how you would get the name out of the string:

var myString = "CN=Rosana Smith,OU=Employees,..";
var myRegexp = /CN=(.*?),/g;
var match = myRegexp.exec(myString);
gs.print(match[1]);

The idea is you want to retrieve the first matching group and not the match itself.  Run it in a Background Script or in  Xplore: Developer Toolkit.

Community Alums
Not applicable
Hi,

var str = "CN=Rosana Smith,OU=Employees,...";
var
mySubString = str.substring( str.lastIndexOf("=") + 1, str.lastIndexOf(",") );
 
Please mark the answer helpful or correct based on the impact of the response. 
 
Reference: https://stackoverflow.com/questions/14867835/get-substring-between-two-characters-using-javascript
 
Thanks
Ishan Parikh