views:

60

answers:

3

I'm trying to pull the name "Dave" (but it will be different depending on who is logged in) out of the following string:

Logged In: Dave - example.com

Any thoughts on the best way to do this with regex in JS?

A: 

split at the colon, split at the spaces, and take the second item in that array, like:

var thestring = "Logged In: Dave - example.com";
thestring = thestring.split(":");
thestring = thestring[1].split(" ");
thename = thestring[1]

Or, if names could contain spaces:

var thestring = "Logged In: Dave - example.com";
    thestring = thestring.split(":");
    thestring = thestring[1].split("-");
    var x = thestring[0].length;
    if (x > 4) { 
    var thename = thestring[0].replace(" ", "");
    }
    else {
    thestring = thestring[0].split(" ");
    thestring = thestring.split(" ");
    thename = thestring[1] + " " + thestring[3];
    }
Liam Bailey
Which would break if the name happens to contain spaces.
cHao
+2  A: 

You don't really need a regex. You could take a .slice() of the string, getting the position of the : and the - using .indexOf().

Example: http://jsfiddle.net/mkUzv/1/

var str = "Logged In: Dave - example.com";

var name = str.slice( str.indexOf(': ') + 2, str.indexOf(' -') );

EDIT: As noted by @cHao, + 2 should have been used in order to eliminate the space after the :. Fixed.

patrick dw
Would that be +2 rather than +1? The space shouldn't be part of the name...
cHao
@cHao - Very good point. I'll update. Thanks. :o)
patrick dw
For the sake of argument, an advantage to using a regex might be that it allows the "logic" of how the to-be-extracted text is embedded to be separated from in-line Javascript code. Thus if that "Logged In" string gets changed for some reason, all you'd have to do is fix the regex and the code that uses it could (probably) stay the same. I agree however that it may be overkill.
Pointy
@Pointy - I see what you mean. This would certainly be not quite as easy to maintain in the event of a change in the layout of the string. +1
patrick dw
+2  A: 

I don't know how you have things exactly, setup, but this should work:

// This is our RegEx pattern.
var user_pattern = /Logged In: ([a-z]+) - example\.com/i

// This is the logged in string we'll be matching the pattern against
var logged_in_string = "Logged In: Dave - example.com"

// Now we attempt the actual match. If successful, user[1] will be the user's name.
var user = logged_in_string.match(user_pattern)

My example is lazy and only matches single names that contain letters between a-z because I wasn't sure of your parameters for the username. You can look up additional RegEx patterns depending on your needs.

Hope this helps!

George Mandis
This worked great! thanks mate.
dave