Getting the last element of a split string array

sol picture sol · Mar 16, 2009 · Viewed 284.7k times · Source

I need to get the last element of a split array with multiple separators. The separators are commas and space. If there are no separators it should return the original string.

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?

Answer

Guffa picture Guffa · Mar 16, 2009

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

var output = input.split(/[, ]+/).pop();