Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

JavaScript/REGEX: First word in a string that contains an underscore

Using JavaScript, how can I get the first word in a string that contains an underscore?

alert( getF('hello world abc_xyz test test_123') ); // should alert "abc_xyz"

function getF (str) {
 return str.replace(' selected','');
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Let me know if that works for you.

I've assumed you won't have a _ character at the start or end of the "word" you're targeting.
@TerryAtOpus
I've assumed you won't have a _ character at the start or end of the "word" you're targeting.
Have you?    ; )
Alternative
function getF(str)
{
   var match = str.match(/\w+\_\w+/);
   return (match != null)?match[0]:'not found';
}

Open in new window

Change the w+ to w* depending on whether you want to enforce can / can't start / end with '_'
@julianH
Change the w+ to w* depending on whether you want to enforce can / can't start / end with '_'
As I teased Terry, "\w" encompasses underscore, so changing the + to * (and vice versa) has no bearing on whether or not the "word" can start with an underscore. Your pattern begins and ends with "\w"--any matching word can start or end with an underscore by default  = )
I know - but it works :) I found out by accident - haven't quite figured out exactly why yet but if you change the \w+\_\w+ to \w*\_\w+ the it allows '_this' whereas it does not in the former.

Same for\w+\_\w* matches 'this_'
Never mind, you're correct. (I really should stop making comments during insomnia fits.) My apologies  = )
The point I was making was that either pattern would match "this__" (two underscores at the end).
Never mind, you're correct. (I really should stop making comments during insomnia fits.) My apologies  = )

You too? - I thought only I did that :) Not that it came across like that ...

You are correct on the double underscore - tradeoff between simplicty and absolute correctness I suppose. I would tend to go with the cater for all eventualities in which case my solution would not pass muster - but if the author is coninced that the data won't contain a double underscore then he should be ok.