본문 바로가기
프로그래밍/JavaScript

[Javascript] 유용한 자바스크립트 함수 모음

by bits 2021. 1. 6.

웹 개발 시 유용하게 사용할 수 있는 자바스크립트 함수를 정리해 볼까 합니다.

 

1. 문자열에서 콤마 제거

// 문자열에서 콤마 제거
function fn_parseNumber(num) {
    return ("" + num).replace(/,/g, "");
}

 

2. 숫자에 콤마 넣기

// 숫자에 콤마 넣기
function fn_numberFormat(num){
    var regexp = /\B(?=(\d{3})+(?!\d))/g;
    return num.toString().replace(regexp, ",");
}

 

3. 숫자인지 확인

// 숫자인지 확인
function fn_isNumber(val){
    var pattern = /^[0-9]*$/;
    return pattern.test(val);
}

 

 

4. 숫자만 입력

// 숫자만 입력
function fn_inputNumber(){
    if(event.keyCode < 48 || event.keyCode > 57){   // 0 ~ 9 범위가 아니면 리턴 false
        event.returnValue = false;
    }
}

위와 같이 별도의 자바스크립트 함수를 만들지 않고 HTML 상에서 처리도 가능하다.

<input type="text" maxlength="10" onKeyup="this.value=this.value.replace(/[^0-9]/g,'');"/>

 

5. 자바스크립트 String 기본 객체에 startsWith() 함수 만들기

자바스크립트에서 기본으로 제공하는 String 객체에 startsWith() 함수를 추가합니다. 브라우저에 따라 startsWith() 함수가 정의되어 있지 않은 경우 아래와 같이 새롭게 정의하여 사용할 수 있습니다.

 

$(function(){

    // String 객체에 startsWith 함수가 정의되어 있지 않으면 선언.(사파리 브라우저의 경우 startWith 함수가 없음.)
    if(!String.prototype.startsWith){
        String.prototype.startsWith = function(searchString, position){
            return this.substring(position || 0, searchString.length) === searchString;
        };
    }

    //  사용예시
    var hostname = location.hostname;
    
    if(hostname.startsWith("localhost")){
        alert("로컬호스트..");
    }

});

6. jQuery load() 함수를 이용한 페이지 이동 및 history 개체에 이동한 페이지를 추가하기

참고로 load() 함수 사용 시 주의할 점은 same-origin-policy 정책이 적용되므로 동일 도메인에서 사용할 수 있습니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>

/*
* url : 이동할 페이지 주소
* data : 페이지로 넘겨줄 데이터
* callback : 페이지 이동 후 호출할 콜백함수
*/
function fn_linkPage(url, data, callback){
    if(arguments.length > 1){
        if(typeof arguments[1] == "function"){
            callback = data;
            data = null;
        }
    }
    // callback 함수가 없으면 기본 함수 셋팅.
    if(!callback){
        callback = function(){
            alert(status + "페이지 로딩 완료 : " + window.location.hash);
        }
    }

    /*
    $("#container").load(url, data, function(response, status, xhr){
        alert(status + "페이지 로딩 완료 : " + window.location.hash);
        // location.href.replace();
        // window.history.replaceState;
    });
    */

    $("#container").load(url, data, callback);
    // window.history.forward();
    // history.pushState(data, null, url);     // 이동한 페이지 주소를 history에 추가한다.
    // window.location.hash = url;

}

// 사용예
fn_linkPage("test.html");
fn_linkPage("test.html #article", {name:'hong', age:20}); // 특정 id에 해당하는 부분만 가져오기
fn_linkPage("test.html", {name:'hong', age:20}, fn_callback);

function fn_callback(){
	alert("콜백함수 실행..");
}


</script>

</head>
<body>

    <h3>Index.html</h3>

    <div id="container">
        내용 페이지 영역
    </div>
    
</body>
</html>

7. 전화번호 포맷팅하기

화면 입력 폼에서 자주 사용하는 전화번호 포맷팅 적용하기

예) 01012345678 => 010-1234-5678 로 변환

// 전화번호 포맷팅.
function fn_phoneFormat(obj){
    if(typeof obj == "string"){
        return fn_phoneFormatString(obj);
    } else if(typeof obj == "object"){
        obj.value = fn_phoneFormatString(obj.value);
    }
}

// 전화번호 포맷팅.
function fn_phoneFormatString(phoneNo){
    var regexp = /(^02.{0}|^01.{1}|[0-9]{3})([0-9]+)([0-9]{4})/;
    return phoneNo.replace(regexp, "$1-$2-$3");
}

8. 문자열에서 특정 구분자(delimeter)로 들어온 문자를 str 에서 제거하기

// delim 로 들어온 문자를 str에서 제거한다.
function fn_removeCharAll(str, delim){
    var regexp = eval("/" + delim + "/gi");
    return str.replace(regexp, "");
}

9. form 입력항목 validation 체크하기

form 태그 내의 입력항목의 필수 입력 체크하기, 입력항목의 id 값을 기준으로 체크하므로 각각의 입력항목에는 id가 부여되어야 함.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>

// 입력항목 validation 체크
// elements : 입력항목 id를 배열형태로 제공
function fn_validateEmpty(elements){
    for(var i = 0; i < elements.length; i++){
        var obj = $("#" + elements[i]);
        if(obj.length == 0){  // if(obj.val() == undefined){
            alert(elements[i] + " 항목이 화면에 존재하지 않습니다.");
        } else {
            if(obj.val().trim() == ""){
                alert(obj.attr("title") + "은 필수입력 항목입니다.");
            }
        }
    }
}

// 사용예시
function fn_submit(){  
	// validation 할 입력항목의 id 를 배열로 제공한다.
    fn_validateEmpty(["name", "email"]);
}

</script>

</head>
<body>

<!-- 화면예시 -->
<form id="frm" name="frm">
    <input type="text" id="name" title="이름">
    <input type="text" id="email" title="이메일">
    <button type="button" onclick="fn_submit();">전송</button>
</form>

</body>
</html>

 

댓글