나를 제외한 천재들 블로그


- 'JavaScript/코드' 카테고리의 글 목록 -

JavaScript/코드

    [JS] 소수점 존재여부 확인하기

    [JS] 소수점 존재여부 확인하기

    코드 function hasDecimal(number) { return number % 1 !== 0; } hasDecimal(123); // false hasDecimal(123.45); // true number % 1은 숫자를 1로 나눈 나머지를 계산하는데, 정수가 아니면 0이 아닌 값을 반환하는 점을 이용한 코드입니다. 자바스크립트에서는 문자열에 대해서 나머지 연산자를 사용해면 똑같은 0의 결과가 나오게 됩니다. 오직 숫자만 판별하기 function hasDecimal(number) { return typeof number === 'number' && number % 1 !== 0; } hasDecimal('123.45'); // false hasDecimal(123.45); // true 숫자가..

    [JS] 영어 첫글자만 대문자로 바꾸기

    [JS] 영어 첫글자만 대문자로 바꾸기

    코드예제 See the Pen <a href="https://codepen.io/hyukson/pen/GRwjjqe"> Untitled</a> by hyukson (<a href="https://codepen.io/hyukson">@hyukson</a>) on <a href="https://codepen.io">CodePen</a>. 코드 function toCapitalize(str) { return str.replace(/\b\w/g, (match) => match.toUpperCase()); } // : 사용예시 toCapitalize('hello world'); // 'Hello World' 코드풀이 'ABC'.replace(/\b\..

    [JS] 길게 클릭(롱클릭) 이벤트 만들기

    [JS] 길게 클릭(롱클릭) 이벤트 만들기

    특정 요소를 정한 시간만큼 누르고 있는 행동을 Long-Click 또는 Long-Press라고 합니다. 예제코드 See the Pen Long Click by hyukson (@hyukson) on CodePen. 코드 const onlongclick = ($target, duration, callback) => { $target.onmousedown = () => { const timer = setTimeout(callback, duration); $target.onmouseup = () => { clearTimeout(timer); }; }; } 마우스로 해당 타깃을 누르는 시점을 mousedown 이벤트로 감지해 주고 특정 시간만의 setTimeout 함수를 실행해 줍니다. 만약 특정시간이 지나기 ..

    [JS] 접속한 브라우저 체크하기

    [JS] 접속한 브라우저 체크하기

    예시코드 See the Pen Untitled by hyukson (@hyukson) on CodePen. 전체 코드 function getBrowser() { const browsers = [ 'Chrome', 'Opera', 'WebTV', 'Whale', 'Beonex', 'Chimera', 'NetPositive', 'Phoenix', 'Firefox', 'Safari', 'SkipStone', 'Netscape', 'Mozilla', ]; const userAgent = window.navigator.userAgent.toLowerCase(); if (userAgent.includes("edg")) { return "Edge"; } if (userAgent.includes("trident") |..

    [JS] 숫자를 한글로 표시하기

    GitHub - hyukson/hangul-util: 한글 관련 자바스크립트 유틸 라이브러리입니다. 한글 관련 자바스크립트 유틸 라이브러리입니다. Contribute to hyukson/hangul-util development by creating an account on GitHub. github.com 'hangul-util' 라이브러리 코드를 기반으로 작성된 포스트입니다. formatNumber(123456789); // 1억 2345만 6789 formatNumberAll(123456789); // 일억 이천삼백사십오만 육천칠백팔십구 예제 코드 See the Pen formatNumber by hyukson (@hyukson) on CodePen. 4자리 대상 (전체코드) 더보기 const th..

    [JS] 초성검색 구현하기

    GitHub - hyukson/hangul-util: 한글 관련 자바스크립트 유틸 라이브러리입니다. 한글 관련 자바스크립트 유틸 라이브러리입니다. Contribute to hyukson/hangul-util development by creating an account on GitHub. github.com 'hangul-util' 코드와 '한글 초성, 중성, 종성 구하기' 포스트를 기반으로 작성된 글입니다. includeByCho('ㄱ', '귤') // true includeByCho('ㅅ과', '사과') // true 코드 예시 See the Pen includeByCho by hyukson (@hyukson) on CodePen. 코드 const CHO_HANGUL = [ 'ㄱ', 'ㄲ', 'ㄴ',..

    [JS] 배열 순서 바꾸기 (맞교환)

    splice() 메서드에 대해서 // Array.splice(시작위치, 삭제할 아이템 개수, 추가할 아이템) const array = [1, 2, 3]; array.splice(0, 1); // [1] array.splice(0, 0, 5); // [] console.log(array); // [5, 2, 3] splice() 메서드의 두 번째 인자는 삭제할 개수입니다. (1은 fromIndex 위치의 value 값) 두 번째 인자의 값이 0일 시, value 값이 제거되지 않습니다. 세 번째 인자 값에는 배열에 추가할 요소입니다. (없을 시 제거만 진행) Array.splice() 메서드는 원본배열에 직접적인 관여를 합니다. (참조) 위치 이동하기 function moveValue(array, from..

    [JS] 한글 초성, 중성, 종성 구하기

    GitHub - hyukson/hangul-util: 한글 관련 자바스크립트 유틸 라이브러리입니다. 한글 관련 자바스크립트 유틸 라이브러리입니다. Contribute to hyukson/hangul-util development by creating an account on GitHub. github.com 'hangul-util' 라이브러리 코드를 기반으로 작성된 포스트입니다. divideHangul('사과') // ['ㅅ', 'ㅏ', 'ㄱ', 'ㅗ', 'ㅏ'] divideHangul("값싼"); // ['ㄱ', 'ㅏ', 'ㅂ', 'ㅅ', 'ㅆ', 'ㅏ', 'ㄴ'] 코드 예시 See the Pen Untitled by hyukson (@hyukson) on CodePen. (전체코드 67줄) 더보기 c..

    [JS] Form Submit 동작 막기 (ft. Button Submit)

    주로 submit 동작에는 Form 데이터를 서버에 전송하고, 와 같이 페이지 이동이 발생합니다. 예제 코드 See the Pen Stop form Submission by hyukson (@hyukson) on CodePen. HTML 코드 (Basic) 로그인 1. 모든 submit 동작 막기 (JavaScript) const $form = document.querySelecotr('form'); $form.addEventListener("submit", (event) => { // 동작(이벤트)을 실행하지 못하게 막는 메서드입니다. event.preventDefault(); console.log(event.target); }); “event.preventDefault()”는 브라우저에 동작하는 이벤..

    [JS] 객체 value 값으로 정렬 시키기

    객체를 value 값을 기준으로 sort() 시켜 줄 수 있게 데이터를 변환시켜 주는 과정이 필요합니다. 코드 const fruits = { Apple: 4000, Banana: 10000, Cherry: 800, Kiwi: 7000, }; const object = Object.fromEntries( Object.entries(fruits).sort((a, b) => a[1] - b[1]) ); console.log(object); // { "Apple": 4000, "Banana": 10000, "Cherry": 800, "Kiwi": 7000 } sort() 메서드를 이용하기 위해서 배열로 변환시킨 후, 다시 객체로 만들어 주는 방법을 거쳐줍니다. 코드 풀이 const fruits = { Apple..

    [JS] 배열을 객체로 변환 (Array to Object)

    Object.fromEntries() 메서드 const entries = [ ['first', 'apple'], ['second', 7], ]; const object = Object.fromEntries(entries); console.log(object); // {'first': 'apple', 'second': 7} 다음과 같이 key-value 형식으로 갖추어진 배열은 Object.fromEntries() 메서드를 사용하면 객체로 변환하여 반환해 줍니다. forEach(), reduce() 메서드 const array = ['apple', 'banana', 'mango']; // 1. const object = {}; array.forEach((value, index) => { object[ind..

    [JS] 특정 영역 밖을 클릭 했을 때 감지하기

    예제코드 See the Pen JS OutsideClick by hyukson (@hyukson) on CodePen. 코드 class useOutsideClick { ref = null; onClickOutside = null; constructor(ref, onClickOutside) { this.ref = ref; this.onClickOutside = onClickOutside; document.addEventListener('mouseup', this.handleClickOutside); } handleClickOutside = (event) => { if (this.ref && !this.ref?.contains?.(event.target)) { this.onClickOutside(this);..