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?
views:
41answers:
4
A:
Hi Jared,
Try this:
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
2010-09-27 19:18:08
and only works if @moo is at the end of the string...
PoweRoy
2010-09-27 19:20:16
A:
david
2010-09-27 19:20:31
How would I do it without the `@`? So it would be `moo`, instead of `@moo`?
Jared
2010-09-27 19:22:15
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
2010-09-27 19:24:30
I am trying to output `moo` without the @, not actually replace the string.
Jared
2010-09-27 19:25:18
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
2010-09-27 19:30:45
A:
You can also avoid regular expressions and have:
var chunks = "the cow went @moo".split("@");
alert(chunks[chunks.length - 1]);
bugventure
2010-09-27 19:56:47