How to use split?

JavascriptSplit

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.

Basically, you just do this:

var array = myString.split(' -- ')

Then your two values are stored in the array - you can get the values like this:

var firstValue = array[0];
var secondValue = array[1];

Solution 3 - Javascript

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ") 

Solution 4 - Javascript

> According to MDN, the split() method divides a String into an > ordered set of substrings, puts these substrings into an array, and > returns the array.

 Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

## In your case ##

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - JavascriptCharles BoyungView Answer on Stackoverflow
Solution 3 - JavascriptvittoreView Answer on Stackoverflow
Solution 4 - JavascriptHasan Sefa OzalpView Answer on Stackoverflow