我的页面上有html片段,它看起来像这样:
...
<address>
6231 Leesburg Pike Ste 100A<br>
Falls Church, VA 22041-2102
</address>
...
如何使用jQuery解析此字符串以获取以下数据:
1. Address: 6231 Leesburg Pike Ste 100A
2. City: Falls Church
3. State: VA
4. ZIP: 22041
谢谢!
答案 0 :(得分:1)
正则表达式:
(.*)\n(.*?),\s([A-Z]{2})\s(\d{5})
使用Javascript:
var str = $("address").text()
var extract = str.match(/(.*)\n(.*?),\s([A-Z]{2})\s(\d{5})/);
var address = extract[1];
var city = extract[2];
var state = extract[3];
var zip = extract[4];
console.log(address) // 6231 Leesburg Pike Ste 100A
console.log(city) // Falls Church
console.log(state) // VA
console.log(zip) // 22041
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<address>
6231 Leesburg Pike Ste 100A<br>
Falls Church, VA 22041-2102
</address>
&#13;
答案 1 :(得分:0)
最实用,假设州/邮政编码中没有其他逗号 - 比oneliner regexp更容易阅读和更易于维护
jQuery仅用于获取和设置HTML - innerHTML可用于完全不需要jQuery
$(function() {
var addr = $("address").html(),
parts1 = addr.replace(/\s+/g, " ").split(/<br>/i),
parts2 = parts1[1].split(","),
parts3 = parts2[1].trim().split(" "),
address = parts1[0].trim(),
city = parts2[0].trim(),
state = parts3[0].trim(),
zip = parts3[1].trim(); // spirit on - if you need first part only
$("ol").after("<ol><li>Address: "+address+
"</li><li>City: "+city+
"</li><li>State: "+state+
"</li><li>Zip: "+zip+"</li>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<address>
6231 Leesburg Pike Ste 100A<br>
Falls Church, VA 22041-2102
</address>
<ol>
<li>Address: 6231 Leesburg Pike Ste 100A</li>
<li>City: Falls Church</li>
<li>State: VA</li>
<li>ZIP: 22041-2102</li>
</ol>
&#13;
答案 2 :(得分:0)
console.log(`<address>
6231 Leesburg Pike Ste 100A<br>
Falls Church, VA 22041-2102
</address>`.match(/(\d+.*)<br>\n\t?(.*), (\w+) ([\d-]+)/))
&#13;
不需要jQuery
答案 3 :(得分:0)
<address>[^\d]*(\d{1,4}[^<,]*)(?:<br\/?>|,)\s*([^,]*),\s*([A-Z]{2})\s*(\d{3,5})[^<]*<\/address>
击穿
<address> = start anchor
[^\d]* = eat all non digits
(\d{1,4}[^<,]*) Capture address
(?:<br\/?>|,)\s* eat to a <br> or comma
([^,]*) = Capture city
([A-Z]{2}) = capture state code
(\d{3,5}) = capture zip
[^<]* = eat rest too anchor
<\/address> = end anchor
var str = "<address>\
6231 Leesburg Pike Ste 100A<br>\
Falls Church, VA 22041-2102\
</address>";
console.log(str.match(/<address>[^\d]*(\d{1,4}[^<,]*)(?:<br\/?>|,)\s*([^,]*),\s*([A-Z]{2})\s*(\d{3,5})[^<]*<\/address>/))