<form>
<h2>초성검색</h2>
<p>(검색어 - 사과, 수박, 멜론, 파인애플, 산딸기, 딸기, 망고)</p>
<input type="text" oninput="_events(this)" placeholder="텍스트를 입력해주세요.">
<div>
<p class='docs'>결과: <span></span> </p>
</div>
</form>
form {
width: 500px;
padding: 1.5rem 1.6rem;
box-shadow: 0 0 1rem rgba(0, 0, 0, .05);
border-radius: 5px;
display: flex;
flex-direction: column;
justify-content: center;
background: #fff;
}
div {
margin: .6rem 0;
}
/* ---- */
@import url("https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
word-break: break-all;
font-family: Pretendard;
}
input {
width: 100%;
height: 3rem;
border-radius: 5px;
padding: 0 1rem;
border: 1px solid #e0e5f6;
background: #fff;
margin: 1rem 0;
}
input::placeholder {
font-size: 1rem;
}
p {
font-size: 0.95rem;
color: #777;
}
p span {
font-size: 1rem;
color: #000;
font-weight: 500;
}
body {
background: #f7f8fc;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
const CHO_HANGUL = [
'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ',
'ㄹ', 'ㅁ', 'ㅂ','ㅃ', 'ㅅ',
'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ',
'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ',
];
const HANGUL_START_CHARCODE = "가".charCodeAt();
const CHO_PERIOD = Math.floor("까".charCodeAt() - "가".charCodeAt());
const JUNG_PERIOD = Math.floor("개".charCodeAt() - "가".charCodeAt());
function combine(cho, jung, jong) {
return String.fromCharCode(
HANGUL_START_CHARCODE + cho * CHO_PERIOD + jung * JUNG_PERIOD + jong
);
}
// 초성검색
function makeRegexByCho(search = "") {
const regex = CHO_HANGUL.reduce(
(acc, cho, index) =>
acc.replace(
new RegExp(cho, "g"),
`[${combine(index, 0, 0)}-${combine(index + 1, 0, -1)}]`
),
search
);
return new RegExp(`(${regex})`, "g");
}
function includeByCho(search, targetWord) {
return makeRegexByCho(search).test(targetWord);
}
// --------------------------------------
const list = ["사과", "수박", "멜론", "파인애플", "산딸기", "딸기", "망고"];
function _events(target) {
const search = target.value.trim();
const regex = makeRegexByCho(search);
let htmlDummy = "";
list.forEach((item) => {
if (regex.test(item)) {
htmlDummy += item.replace(regex, "<mark>$1</mark>") + ', ';
}
});
document.querySelector(".docs span").innerHTML = search ? htmlDummy : "";
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.