views:

1765

answers:

2

I need to get the last element of the splitted array with multiple seperators. if there's no array it should return the string

the seperators are "commas" and "space"

if the string is "how,are you doing, today?" it should return "today?"

if the input were "hello" the output should be "hello"

how can i do this in javascript

DUPE: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-seperators-in-javascript

+4  A: 
var str = "hello,how,are,you,today?";
var pieces = str.split(/[\s,]+/);

At this point, pieces is an array and pieces.length contains the size of the array so to get the last element of the array, you check pieces[pieces.length-1]. If there are no commas or spaces it will simply output the string as it was given.

alert(pieces[pieces.length-1]); // alerts "today?"
Paolo Bergantino
+10  A: 

There's a one-liner for everything. :)

var output = input.split(/[, ]+/).pop();
Guffa
Aaah, pop. Nicely done. :)
Paolo Bergantino