首页 > 解决方案 > 获取逗号后出现最多的文本字符串,用于任何目的

问题描述

我想用 Jquery 在这个 HTML 中的“,”之后获取下面这段代码中出现次数最多的文本。在这种情况下,文本将返回“Bothell”。我该怎么做呢?

<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bellevue</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Kirkland</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Monroe</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>

从下面的用户那里尝试了此代码,但不起作用:

 let As = document.querySelectorAll("a.address");
let towns = new Map();
for(let a of As)
{
  let town = a.textContent.split(',')[1].trim()
  if(towns.has(town))
  {
    towns.set(town, towns.get(town)+1) 
  }
  else
  {
    towns.set(town, 1);
  }
}
let most = [...towns.entries()].sort((a, b) => b[1] - a[1])[0];
if ($("a.address").length) {
            var signupText = (most);
            $(".rg-modal-signup h2").text('Keep searching ' + signupText + ' real estate.');
        } else {
            var signupText = '';
             $(".rg-modal-signup h2").text('Keep searching for your dream home.');
        }

标签: javascripthtmljquery

解决方案


你必须在这里做多件事:

  1. 提取名称
  2. 计算出现次数
  3. 获得结果最高的那个。

这是您可以根据上面的输入使用的快速代码。请注意,这不考虑多次出现逗号,但我认为您已经可以调整接下来需要的内容。:)

const data = `<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bellevue</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Kirkland</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Monroe</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>`;

const anchors = data.split('\n');

const getName = (row) => {
    const index = row.indexOf(',');
    const commaOffset = 2;
    const suffixOffset = 4;
    const length = row.length;
    return row.substring(index + commaOffset, length - suffixOffset);
}

const names = anchors.map(getName);

const counts = names.reduce((group, name) => {
    if (!group[name]) {
        group[name] = 1;
    } else {
        group[name]++;
    }

    return group;
}, {});

const entries = Object.entries(counts);
const sorted = entries.sort((a, b) => b[1] - a[1])
const hightestCount = sorted.shift();


console.log(hightestCount)

这应该给你:

[ 'Bothell', 4 ]

你知道之后该怎么处理它。祝你好运!


推荐阅读