views:

41

answers:

4

Let says I have a string that says and the cow went @moo, and I want to only select moo... how would I go about that?

A: 

Hi Jared,

Try this:

http://jsfiddle.net/ekYNQ/

var haystack = "the cow ran around and subsequently went @moo";

if (haystack.indexOf("@")) {
    alert(haystack.substr(haystack.indexOf("@") + 1));
}

Of course, this only works for the first instance of @.

treeface
and only works if @moo is at the end of the string...
PoweRoy
A: 

You could use the following regex:

/@[\w]+/g

example: http://jsfiddle.net/3VDQL/

david
How would I do it without the `@`? So it would be `moo`, instead of `@moo`?
Jared
so you want to find an occurence of the word "moo" in your text? then it would boild down to "the cow went moo".replace("moo", "crazy")
david
I am trying to output `moo` without the @, not actually replace the string.
Jared
I guess I could do .replace("moo", "")
Jared
ah okay: see this: http://jsfiddle.net/AKF5a/
david
A: 
var moo = "blah blah cow @moo".match(/@([^ ]*)/)[1];

The regular expression @([^ ]*) means: find the character @, then get all the characters afterward until a space is encountered (or implicitly the end of the string). Any part of the regex enclosed in parenthesis is stored and returned in an array. The first element is always the entire match, in this case @moo, afterwards the match inside each parenthesis in the regex from left to right.

MooGoo
Thank you for your explanation : )
Jared
A: 

You can also avoid regular expressions and have:

 var chunks = "the cow went @moo".split("@");
 alert(chunks[chunks.length - 1]);
bugventure