Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into two parts [duplicate]

Tags:

I know there are several ways to split an array in jQuery but I have a special case: If I have for example this two strings:

 "G09.4 What"
 "A04.3  A new Code"

When I split the first by ' ' I can simply choose the code in front with [0] what would be G09.4. And when I call [1] I get the text: What

But when I do the same with the second string I get for [1] A but I want to retrieve A new Code.

So how can I retrieve for each string the code and the separate text?

like image 590
John Smith Avatar asked Dec 09 '13 15:12

John Smith


People also ask

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

How do you split a single string?

The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.

How do you divide strings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

Use

var someString = "A04.3  A new Code";
var index = someString.indexOf(" ");  // Gets the first index where a space occours
var id = someString.substr(0, index); // Gets the first part
var text = someString.substr(index + 1);  // Gets the text part
like image 175
RononDex Avatar answered Oct 08 '22 03:10

RononDex


You can split the string and shift off the first entry in the returned array. Then join the leftovers e.g.

var chunks = "A04.3  A new Code".split(/\s+/);
var arr = [chunks.shift(), chunks.join(' ')];

// arr[0] = "A04.3"
// arr[1] = "A new Code"
like image 31
Bart Avatar answered Oct 08 '22 02:10

Bart