2017-07-11 74 views
3

我想将下面的输入字符串拆分为输出字符串。
输入= 'ABC1:ABC2:ABC3:ABC4'
输出= [ 'ABC1', 'ABC2:ABC3:ABC4']字符串第一次拆分

let a = 'ABC1:ABC2:ABC3:ABC4' 
a.split(':', 2); // not working returning ['ABC1','ABC2'] 
+0

https://es6console.com/j4zc4icr/ –

回答

3

您可以使用此功能,可以在所有的浏览器

var nString = 'ABC1:ABC2:ABC3:ABC4'; 
 
var result = nString.split(/:(.+)/).slice(0,-1); 
 
console.log(result);

+0

感谢...... :-) – Nithin

1

可以使用indexOfslice

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
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"] 

实施例:https://jsfiddle.net/4nq1tLye/

1

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