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?
-
1split() needs a delimiter to work.nickd– nickd2011年11月28日 19:13:07 +00:00Commented Nov 28, 2011 at 19:13
4 Answers 4
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).
8 Comments
"hello friend".partition(3) ["hel", "lo friend"] doesn't split *POSITION=3 at all for me. Then again, *POSITION=3 is very open to interpretation :D Just putting it out there.Maybe use a simple RegExp match?
var arr = "abc123".match(/^([a-z]+)(\d+)$/i);
arr.shift();
console.log(arr);
Comments
var arr = "this is a test".match(/.{1,3}/g);
Comments
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