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?

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

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 - 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
-1

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];
    }

1 Comment

Which would break if the name happens to contain spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.