joncodo
joncodo

Reputation: 2328

Javascript Split method

var string = abc123;
string.split(*POSITION=3)???

Is there a way to split this string into an array of strings that is [abc,123]? Is the split method the right thing to use?

Upvotes: 1

Views: 1277

Answers (4)

Tracker1
Tracker1

Reputation: 19334

var arr = "this is a test".match(/.{1,3}/g);

Upvotes: 1

Dan Tao
Dan Tao

Reputation: 128317

I would say the split method is not the right thing to use here, as its purpose is to segment a string based on a certain character.

You could certainly write your own function, of course:

function partition(str, index) {
  return [str.substring(0, index), str.substring(index)];
}

// results in ["123", "abc"]
var parts = partition("123abc", 3);

If you wanted to write "123abc".partition(3) instead, you could make that possible by extending String.prototype:

String.prototype.partition = function(index) {
  return [this.substring(0, index), this.substring(index)];
};

Personally, though, I'd recommend avoiding that sort of tomfoolery (search the web for "extending built-in objects in JavaScript" if you want to read what others have to say on the topic).

Upvotes: 2

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

Maybe use a simple RegExp match?

var arr = "abc123".match(/^([a-z]+)(\d+)$/i);
arr.shift();

console.log(arr);

Upvotes: 1

Esailija
Esailija

Reputation: 140210

No but it is trivial to implement that:

function splitn( str, n ){
var r = [], offset = 0, l = str.length;

    while( offset < l ) {
    r.push( str.substr( offset, n ) );
    offset += n;
    }
return r;
}

Then:

var string = "abc123";
console.log( splitn( string, 3 ) );
//["abc", "123"]

Assuming you want similar functionality to str_split

Upvotes: 0

Related Questions