admin管理员组

文章数量:1414858

I'm trying to filter out the first ma and everything before it. Should I just use regex or will split work?

// notice multiple mas, I'm trying to grab everything after the first ma.
str = 'jibberish, text cat dog milk, chocolate, rainbow, snow',

// this gets the text from the first ma but I want everything after it. =(
result = str.split(',')[0];

I'm trying to filter out the first ma and everything before it. Should I just use regex or will split work?

// notice multiple mas, I'm trying to grab everything after the first ma.
str = 'jibberish, text cat dog milk, chocolate, rainbow, snow',

// this gets the text from the first ma but I want everything after it. =(
result = str.split(',')[0];
Share Improve this question edited Jan 19, 2013 at 16:23 Andrew Whitaker 126k32 gold badges295 silver badges308 bronze badges asked Jan 19, 2013 at 16:06 dittoditto 6,32710 gold badges58 silver badges91 bronze badges 1
  • I removed the jquery tag, since this really has nothing to do with jQuery :) – Andrew Whitaker Commented Jan 19, 2013 at 16:23
Add a ment  | 

5 Answers 5

Reset to default 1

Instead of split, try this - it will not mess with any other mas than the first

var result = str.substring(str.indexOf(",")+1)

If you want to skip the leading space, use +2

If you are not sure there will always be a ma, it is safer to do trim

var result = str.substring(str.indexOf(",")+1).trim();

How about using substring and indexOf:

str = str.substring(str.indexOf(",") + 2);

Example: http://jsfiddle/ymuJc/1/

// Convert to array
var arr = str.split(',');

// Remove first element of array
arr.splice(0, 1);

// Convert back to string
var newString = arr.join(', ');

You can simply use the substring to extract the desired string.

Live Demo

result = str.substring(str.indexOf(',')+1); //add 2 if you want to remove leading space

If you want to use split for any reason

Live Demo

result = str.split(',')[0];    
result = str.split(result+",")[1];

you can use substr and indexOf

str = 'jibberish, text cat dog milk, chocolate, rainbow, snow'

result = str.substr(str.indexOf(',')+1, str.length)

本文标签: javascriptFilter out first comma and everything before it using splitStack Overflow