1

我想做一个从某个网站获取一些信息的书签。

使用$('#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

如您所见,一个大字符串中有很多不必要的空格和不同的信息。我想做的是删除所有空格,删除不必要的信息(如电话:,电子邮件:,Spletna stran podjetja)并用逗号分隔重要信息','

是否可以将信息的每个独立部分放入自己的变量中?我的解决方案是类似于php's 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>
4

2 回答 2

3

$('#div').text();并避免 div 内的 html 元素

为什么不使用 HTML 结构而不是丢弃它?而不是 access ,$('#div')为什么不 access $('#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(', ')(电话相同)。

于 2013-09-02T23:29:32.163 回答
2

尝试像这样摆脱连续的空格:

$('#div').text().replace('\n', ' ').replace(/\s\s*/g, ' ');

演示

于 2013-09-02T23:34:53.257 回答