2017-08-24 31 views

回答

2

您可以用replace使用反向引用做到这一点:

var s = "Sat 8-11, Sat 11-18"; 
 

 
s = s.replace(/([a-z]+) (\d+)-(\d+), \1 \3-/i, "$1 $2-"); 
 
console.log(s);

+0

非常聪明! :-) –

0

使用String.prototype.match()功能与特定的正则表达式的解决方案:

var s = "Sat 8-11, Sat 11-18", 
 
    r = s.match(/([A-Z][a-z]+) (\d{1,2})-(\d{1,2}), \1 (\d{1,2})-(\d{1,2})/); 
 

 
// if the input string matches the pattern and the second hour 
 
// in the first interval equals to the first hour in the second interval 
 
if (r.length == 6 && r[3] == r[4]) { 
 
    s = r[1] +' '+ r[2] +'-'+ r[5]; 
 
} 
 
console.log(s)

相关问题