반응형
Type Ahead
Code
<script>
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data))
const findMatches = (wordToMatch, cities) => {
return cities.filter(place => {
const regex = new RegExp(wordToMatch, 'gi');
return place.city.match(regex) || place.state.match(regex);
})
}
const numberWithCommas = (x) => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
const displayMatches = (e) => {
const matchArray = findMatches(e.target.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(e.target.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${e.target.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${e.target.value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(place.population)}</span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
}
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);
</script>
배운점 & 느낀점
이번에는 정규표현식 이해하는데 시간을 많이 썼습니다.
/\B(?=(\d{3})+(?!\d))/g
/B => 단어 사이사이 경계선을 나타냄
(?=) => 조건 합쳐서 확인
(\d{3}) => 숫자 3개
(?!\d) => 숫자가 없는
즉, 숫자 3개가 하나이상 나오며 뒤에 숫자가 아닌 그룹에 ,를 넣는다
1000000 => 1,000,000
반응형
'공부 정리 > jsChallenge' 카테고리의 다른 글
js challenge day 8 (2) | 2023.01.31 |
---|---|
js challenge day 7 (0) | 2023.01.30 |
js challenge day 5 (0) | 2023.01.25 |
js challenge day 4 (0) | 2023.01.24 |
Js challenge day 3 (0) | 2023.01.23 |
댓글