23

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?

user247702
  • 23,641
  • 15
  • 110
  • 157
John Smith
  • 6,105
  • 16
  • 58
  • 109

6 Answers6

46

Use

var someString = "A04.3  A new Code";
var index = someString.indexOf(" ");  // Gets the first index where a space occours
var id = someString.slice(0, index); // Gets the first part
var text = someString.slice(index + 1);  // Gets the text part
RononDex
  • 4,143
  • 22
  • 39
12

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"
Bart
  • 17,070
  • 5
  • 61
  • 80
4

Instead of splitting the string on the space, use a combination of indexOf and slice:

var s = "A04.3 A new Code";
var i = s.indexOf(' ');
var partOne = s.slice(0, i).trim();
var partTwo = s.slice(i + 1, s.length).trim();
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
4

You can use match() and capture what you need via a regular expression:

"G09.4 What".match(/^(\S+)\s+(.+)/)
  // => ["G09.4 What", "G09.4", "What"]

"A04.3  A new Code".match(/^(\S+)\s+(.+)/)
  // => ["A04.3  A new Code", "A04.3", "A new Code"]

As you can see the two items you want are in [1] and [2] of the returned arrays.

James
  • 109,676
  • 31
  • 162
  • 175
3

What about this one:

function split2(str, delim) {
    var parts=str.split(delim);
    return [parts[0], parts.splice(1,parts.length).join(delim)];
}

FIDDLE

Or for more performance, try this:

function split2s(str, delim) {
    var p=str.indexOf(delim);
    if (p !== -1) {
        return [str.substring(0,p), str.substring(p+1)];
    } else {
        return [str];
    }
}
Frederik.L
  • 5,522
  • 2
  • 29
  • 41
0

You can get the code and then remove it from the original string leaving you with both the code and the string without the code.

var originalString = "A04.3  A new Code",
    stringArray = originalString.split(' '),
    code,
    newString;

code = stringArray[0];
newString = originalString.replace(code, '');
Jonathan
  • 1,833
  • 13
  • 15