正则表达式返回数组未定义

时间:2017-01-02 17:54:43

标签: javascript regex

我有字符串,我想通过它获取欲望数据。我在大多数函数中使用它并且它工作正常,但我已经开发了另一个单独的项目并尝试使用它,但每次它都返回数组undefined。

我的字符串如下,我得到数据变量。

var data="<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
Dear Customer,<br>
<br>
We have assigned the following item to one of your employee.<br>
<br>
Item Number: 7372B456<br>
<br>
<strong>Basic Information</strong><br>
Cake type: 4 pounds<br>
Pickup time: Mon, Jan 2, 22:27 (GMT&#43;0500) PAK<br>
Pickup location: Riaz Uddin Ahmed Road - Karachi<br>
<strong>Driver assigned</strong><br>
Name: Imran Aziz<br>
Phone: 788888888888<br>
Baker: NEw horizon bakers<br>
<br>
If you need any help, please feel free to contact our hotline.<br>
<br>
Regards,<br>
<br>
Your Team
</body>
</html>";

var regEx = /\n|:(.*)</ig;
var match = regEx.exec(data);

但每次我都得到未定义的匹配

1 个答案:

答案 0 :(得分:0)

要执行全局匹配(所有出现),你应该在循环中进行。

   var regEx = /:(.*?)<br>/ig;
    while(match = regEx.exec(data)) {
    console.log(match[1]);
    }

没有循环,你只能找到第一个值。

另外,改变(改进,imho)你的正则表达式 - 所以目标现在是组[1]:https://regex101.com/r/U2rOa3/1

要查看正则表达式匹配的内容,请在regex101上查看。当然,第一场比赛是新线......

var data='<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body>Dear Customer,<br><br>We have assigned the following item to one of your employee.<br><br>Item Number: 7372B456<br><br><strong>Basic Information</strong><br>Cake type: 4 pounds<br>Pickup time: Mon, Jan 2, 22:27 (GMT&#43;0500) PAK<br>Pickup location: Riaz Uddin Ahmed Road - Karachi<br><strong>Driver assigned</strong><br>Name: Imran Aziz<br>Phone: 788888888888<br>Baker: NEw horizon bakers<br><br>If you need any help, please feel free to contact our hotline.<br><br>Regards,<br><br>Your Team</body></html>';

var regEx = /:(.*?)<br>/ig;
while(match = regEx.exec(data)) {
console.log(match[1]);
}