JavaScript regex to find word in middle of string
I'm开发者_JAVA百科 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?
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!
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.
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];
}
精彩评论