Javascript在多个跨度之间拆分字符串

时间:2016-03-25 22:32:36

标签: javascript split match

我已经搜索谷歌寻找答案,但我似乎找不到答案。

我需要将以下字符串拆分为单独的变量

字符串存储为变量 : -

var location = autocomplete.getPlace();
var address = location['formatted_address'];

Output:-

<span class="street-address">Street address</span>, <span class="locality">Town</span>, <span class="region">County</span> <span class="postal-code">Post Code</span>, <span class="country-name">Country</span>

例如

var street = "Street address";
var town = "Town";
var county = "County";
var postc = "Post Code";
var country = "Country";

所以我需要获取

之间的内容
 <span class="street-address"></span>
 <span class="locality"></span>
 etc...

有时会有额外的跨度。

我查看过一些javascript,但它只获取以下内容: -

 <span class="locality"> and the very last </span>

正确方向的任何帮助都会非常

4 个答案:

答案 0 :(得分:0)

您使用普通的JavaScript吗?还是jQuery?

在javascript中,您可以通过以下方式获取元素内的文本:

var1 = document.getElementByClass("street-address").innerText

或在jQuery中:

var streetAddress = $('.street-address').text();
var city= $('.city').text();

答案 1 :(得分:0)

如果你正在使用jQuery:

var 1 = $('span.street-address').text();
var 2 = $('span.locality').text();
var 3 = $('span.region').text();
var 4 = $('span.postal-code').text();
var 5 = $('span.country-name').text();

应该这么简单,除非我在问题中遗漏了一些东西。

答案 2 :(得分:0)

你能用jQuery吗?看看https://jsfiddle.net/zsxar4r4/

var address = [];
$('span').each(function(idx, span) {
    address.push($(span).html());
})
console.log(address);

答案 3 :(得分:0)

您可以使用getElementsByClassName()方法,它将返回类似数组的对象。

https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName

var addressData = document.getElementsByClassName('address');

//And than do something with the object. You can access it like an array:

console.log(addressData[2].innerHTML);