제목을 해시태그로 자동 변환 소스코드
소스코드
<script>
$(function() {
// 기존 Tagify 초기화 코드
const all_tags = <?php echo $js_array; ?>;
const tags = Array.isArray(all_tags) ? all_tags.map((a) => a.tag) : [];
const input = document.querySelector('input[name=wr_tag]');
const tagify = new Tagify(input, {
whitelist: tags,
dropdown: {
position: "input",
enabled: 0
},
});
// 금지된 단어 목록 (배열로 관리)
const forbiddenWords = ["제목에", "입력하면", "작성자", "내용"];
// 제목 입력이 완료된 후 해시태그 자동 입력
const subjectInput = document.getElementById('wr_subject');
const tagInput = document.getElementById('wr_tag');
// 제목 입력 후 input 요소에서 focus가 벗어나면 (blur 이벤트 발생 시)
subjectInput.addEventListener('blur', function() {
const titleValue = subjectInput.value.trim();
if (titleValue && !tagInput.value) {
// 특수문자 및 불필요한 문자를 공백으로 치환
const cleanedTitle = titleValue
.replace(/[^a-zA-Z0-9가-힣\s]/g, ' ') // 모든 특수문자 제거하고 공백으로 변환
.replace(/\s+/g, ' ') // 여러 공백을 하나로 치환
.trim(); // 앞뒤 공백 제거
// 제목을 공백 기준으로 정확하게 분리하고 금지된 단어 제외
const words = cleanedTitle
.split(' ') // 공백을 기준으로 단어 분리
.filter(word => word && !forbiddenWords.includes(word)); // 금지된 단어 필터링
// 변환된 해시태그 값 로그로 확인 (디버깅용)
console.log("변환된 해시태그 값:", words);
// Tagify로 각 단어를 해시태그로 추가
tagify.addTags(words); // Tagify 라이브러리 사용
}
});
});
</script>