我想做一个小书签,从某个网站获取一些信息。
在使用 $('#div').text();
并避开 div 内的 html 元素后,我得到以下字符串:
TOP-GOST d.o.o. Tel: 01 200 50 80 , 041 843 303 E-mail: info@via-bona.com Spletna stran podjetja Tbilisijska ulica 59 1000 Ljubljana Slovenija
如您所见,一个大字符串中有很多不必要的空格和不同的信息。我想做的是删除所有空格,删除不必要的信息(如 Tel:、E-mail:、Spletna stran podjetja)并用逗号分隔重要信息 ','
。
是否可以将信息的每个独立部分放入其自己的变量中?我的解决方案类似于 php 的 explode()
或反向 javascript join()
,在用逗号将片段粘在一起之后。
关于删除不需要的部分,是使用.replace()。
好主意吗?
期望的结果:
variable one_string = 'TOP-GOST d.o.o., 012005080, 041843303, info@via-bona.com, Tbilisijska u...';
AND LATER
variable title = 'TOP-GOST d.o.o.'
variable phone = '012005080,041843303'
variable email = 'info@via-bona.com'
etc.
原始源代码 HTML:
<div class="offer-contact">
<h3 class="offer-company">
TOP-GOST d.o.o.</h3>
<strong>
Tel:
</strong>
01 200 50 80 , 041 843 303<br>
<strong>
E-mail:</strong> <a href="mailto:info@via-bona.com">
info@via-bona.com</a><br>
<strong>
<a href="http://www.via-bona.com" target="_blank">Spletna stran podjetja</a><br>
</strong></div><strong>
<div class="offer-map">
<p>
Tbilisijska ulica 59<br>
1000 Ljubljana <br>
Slovenija<br>
</p>
</div>
最佳答案
$('#div').text();
and avoiding the html elements that are inside the div
为什么不使用 HTML 结构而不是丢弃它?为什么不访问 $('#div')
,而不是访问 $('#phone')
,$('#email')
... 分别地?如果他们没有 ID,但具有稳定的结构,您可以使用 $('#div > div:nth-child(3)')
类型的选择器来确定您要查找的内容.
编辑:现在我们可以看到结构:
var title = $('.offer-company').text().trim();
var email = $('.offer-contact a').attr('href').trim();
var address_array = $.map($('.offer-map p').html().split('<br>'), function(v) {
var t = v.trim();
if (t.length) return t;
});
// Phone is trickier; it's not in a tag by itself. So, this
// is the more reliable method (get rid of everything else):
var $offer = $('.offer_contact').clone();
$offer.find('.offer-company, strong, br, a').remove()
var phone_array = $.map($offer.html().split(','), function(v) {
var t = v.trim();
if (t.length) return t;
});
// The alternative would have been to go with regexp, which
// is not recommended for cutting up HTML.
像这样的东西应该可以做到。如果您需要逗号分隔的地址或电话字符串,您可以执行 address_array.join(', ')
(电话相同)。
关于Javascript : long string to smaller pieces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18581995/