String Split the first time only
I want to split the bottom line of input as line of output.
Input = 'ABC1: ABC2: ABC3: ABC4'
Output = ['ABC1', 'ABC2: ABC3: ABC4']
let a = 'ABC1:ABC2:ABC3:ABC4'
a.split(':', 2); // not working returning ['ABC1','ABC2']
+3
Nithin
source
to share
4 answers
You can use this, works in all browsers
var nString = 'ABC1:ABC2:ABC3:ABC4';
var result = nString.split(/:(.+)/).slice(0,-1);
console.log(result);
+3
Ankit agarwal
source
to share
You can use indexOf
and slice
:
var a = 'ABC1:ABC2:ABC3:ABC4';
var indexToSplit = a.indexOf(':');
var first = a.slice(0, indexToSplit);
var second = a.slice(indexToSplit + 1);
console.log(first);
console.log(second);
+1
Alberto trindade tavares
source
to share
let a = 'ABC1:ABC2:ABC3:ABC4'
const head = a.split(':', 1);
const tail = a.split(':').splice(1);
const result = head.concat(tail.join(':'));
console.log(result); // ==> ["ABC1", "ABC2:ABC3:ABC4"]
Example: https://jsfiddle.net/4nq1tLye/
+1
Mikhail Shabrikov
source
to share
+1
Slava Utesinov
source
to share