开发者

How do I select string after a specific symbol in javascript/Jquery?

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?


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.


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 @.


You could use the following regex:

/@[\w]+/g

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


You can also avoid regular expressions and have:

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


I am here using underscore, you can use any character instead of it.

new_string = your_string.split('_').pop().trim();


It is really easy, you can use two functions together to get your specific result. I am here using underscore, you can use any character instead of it.

new_string = your_string.split('_').pop().trim();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜