How to use split?

Matt picture Matt · Mar 31, 2010 · Viewed 310.2k times · Source

I need to break apart a string that always looks like this:

something -- something_else.

I need to put "something_else" in another input field. Currently, this string example is being added to an HTML table row on the fly like this:

tRow.append($('<td>').text($('[id$=txtEntry2]').val()));

I figure "split" is the way to go, but there is very little documentation that I can find.

Answer

Felix Kling picture Felix Kling · Mar 31, 2010

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));