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


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);
      

Run codeHide result


+3


source


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);
      

Run codeHide result


+1


source


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


source


console.log('ABC1:ABC2:ABC3:ABC4'.replace(':','@').split('@'));
      

Run codeHide result


+1


source







All Articles