Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tách chuỗi phân cách dấu gạch ngang có số âm/khoảng - JavaScript

Chuỗi "John-Smith-90-100-US" và "David-Miller--120-AUS". Dùng regex /-(?=[A-Za-z-]|\d+-\d)/ tách đúng, giữ nguyên khoảng số âm.

Mã thực hiện

var firstValue = "John-Smith-90-100-US";
var secondValue = "David-Miller--120-AUS";
var regex = /-(?=[A-Za-z-]|\d+-\d)/;
console.log(firstValue.split(regex));
console.log(secondValue.split(regex));

Kết quả

[ 'John', 'Smith', '90-100', 'US' ]
[ 'David', 'Miller', '-120', 'AUS' ]