Filter out the first comma and that's all before using split

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

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

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

      

+3


source to share


5 answers


Instead of separating, try this - it won't be confused with any other commas than the first

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

      

If you want to skip leading space use +2



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

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

      

+1


source


You can just use a substring to extract the string you want.

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];

      

+1


source


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

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

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

      

+1


source


How about using substring

and indexOf

:

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

      

Example: http://jsfiddle.net/ymuJc/1/

+1


source


you can use substr

andindexOf

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

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

      

0


source







All Articles