Javascript, 전화번호 형식으로 변경하는 함수

사용자가 원하는 형식으로 전화를 입력했을때 정해진 형식(xx-xxx-xxxx)으로 변경해주는 함수입니다.

const formatPhoneNumber = (input) => {
    const cleanInput = input.replaceAll(/[^0-9]/g, "");
    let result = "";
    const length = cleanInput.length;

    if(length === 8) {
        result = cleanInput.replace(/(\d{4})(\d{4})/, '$1-$2');
    } else if(cleanInput.startsWith("02") && (length === 9 || length === 10)) {
        result = cleanInput.replace(/(\d{2})(\d{3,4})(\d{4})/, '$1-$2-$3');
    } else if(!cleanInput.startsWith("02") && (length === 10 || length === 11)) {
        result = cleanInput.replace(/(\d{3})(\d{3,4})(\d{4})/, '$1-$2-$3');
    } else {
        result = undefined;
    }

    console.log(`${input} -> ${result}`);

    return result;
}

테스트를 위해 다음 코드를 실행해 보면..

formatPhoneNumber("08032332333");
formatPhoneNumber("021231234");
formatPhoneNumber("(02)12351234");
formatPhoneNumber("63633221");
formatPhoneNumber("010-9543-3224");
formatPhoneNumber("0625252312");
formatPhoneNumber("03112341234");

결과는 다음과 같습니다.

021231234 -> 02-123-1234
08032332333 -> 080-3233-2333
021231234 -> 02-123-1234
(02)12351234 -> 02-1235-1234
63633221 -> 6363-3221
010-9543-3224 -> 010-9543-3224
0625252312 -> 062-525-2312
03112341234 -> 031-1234-1234

인지하지 못한 전화번호 형식이 있을 수 있으니 개선해서 사용하시면 됩니다.

웹 3D 라이브러리(Three.js)를 이용한 메타버스 환경 구축 및 인터랙티브 웹 개발

안녕하세요, GIS Developer 김형준입니다.

오는 5월 25일부터 3일간 메타버스 환경 구축 및 인터랙티브 웹 개발이라는 주제를 가지고 강의를 진행합니다. 메타버스 환경 구축은 Blender라는 3차원 모델링 툴을 사용하고 인터렉티브 웹 개발은 three.js 라이브러리를 활용합니다. Javascript을 이미 알고 있다는 가정 하에 Blender나 three.js를 전혀 모르시는 분들도 이해하실 수 있도록 진행할 계획입니다.

아래의 영상은 교육 내용 중 실습 예제 중 하나입니다.

교육장소는 서울 판교에 있는 메타버스 캠퍼스입니다. 교육비는 무료이지만 참여할 수 있는 인원 수에 제한이 있습니다. 참여 신청을 위한 링크는 아래의 이미지를 클릭하시면 됩니다. 많은 참여 바랍니다.

[THREE.JS] Blooming Earth

원하는 결과는 다음과 같습니다.

장면에 추가된 모델은 3개입니다. 지구 본체, 지구 주변의 푸른 빛(Blooming Light), 지구 주위의 하얀 작은 무수한 별들.

먼저 지구 본체에 대한 코드입니다.

const sphere = new THREE.Mesh(
    new THREE.SphereGeometry(5, 50, 50), 
    new THREE.ShaderMaterial({
        uniforms: {
            globeTexture: {
                value: new THREE.TextureLoader().load("data/earth.jpg")
            }
        },
        vertexShader: `
            varying vec2 vertexUV;
            varying vec3 vertexNormal;

            void main() {
                vertexUV = uv;
                vertexNormal = normalize(normalMatrix * normal);

                gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
            }
        `,
        fragmentShader: `
            uniform sampler2D globeTexture;

            varying vec2 vertexUV;

            void main() {
                vec4 color = texture2D(globeTexture, vertexUV);
                gl_FragColor = vec4(color.xyz, 1.);
            }
        `
    })
);

결과는 다음과 같습니다.

지구 가장자리가 어두워서 가장자리를 밝게 만들기 위해 위의 코드에서 fragmentShader 코드를 다음처럼 변경합니다.

fragmentShader: `
    uniform sampler2D globeTexture;

    varying vec2 vertexUV;
    varying vec3 vertexNormal;

    void main() {
        float intensity = 1.05 - dot(vertexNormal, vec3(0.,0.,1.));
        vec3 atmosphere = vec3(0.3, 0.6, 1.0) * pow(intensity, 1.5);

        vec4 color = texture2D(globeTexture, vertexUV);
        gl_FragColor = vec4(atmosphere + color.xyz, 1.);
    }
`,

결과는 다음과 같습니다.

지구 주변의 푸른 빛(Blooming Light)에 대한 코드입니다.

const atmosphere = new THREE.Mesh(
    new THREE.SphereGeometry(5, 50, 50),
    new THREE.ShaderMaterial({
        vertexShader: `
            varying vec3 vertexNormal;

            void main() {
                vertexNormal = normalize(normalMatrix * normal);
                gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
            }
        `,
        fragmentShader: `
            varying vec3 vertexNormal;

            void main() {
                float intensity = pow(0.76 - dot(vertexNormal, vec3(0,0,1.)), 2.0);
                gl_FragColor = vec4(0.3, 0.6, 1.0, 1) * intensity;
            }
        `,
        transparent: true,
        blending: THREE.AdditiveBlending,
        side: THREE.BackSide
    })
);
atmosphere.scale.set(1.2, 1.2, 1.2);

결과는 다음과 같습니다.

이제 지구 주위의 하얀 작은 무수한 별들에 대한 코드입니다.

const starGeometry = new THREE.BufferGeometry();

const starVertices = [];
for(let i=0; i<10000; i++) {
    const x = (Math.random() - 0.5) * 1000; 
    const y = (Math.random() - 0.5) * 1000; 
    const z = (Math.random() - 0.5) * 1000; 
    starVertices.push(x, y, z);
}

starGeometry.setAttribute("position", new THREE.Float32BufferAttribute(starVertices, 3));

const starMaterial = new THREE.PointsMaterial({color: 0xffffff});
const stars = new THREE.Points(starGeometry, starMaterial);
this._scene.add(stars);

결과는 이 글의 가장 첫번째 이미지와 같습니다.

CryptoJS를 이용한 AES256 암호화 / 복호화

자바스크립트에서 CryptoJS 라이브러리를 사용하여 AES256 방식으로 데이터를 암호화하기 위한 함수는 다음과 같습니다.

encodeByAES56(key, data){
    const cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(""),
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
    });

    return cipher.toString();
}

위의 함수를 사용하는 예는 다음과 같구요.

const k = "key";
const rk = k.padEnd(32, " "); // AES256은 key 길이가 32자여야 함
const b = "암호화는 보안을 위해 매우 중요합니다.";
const eb = this.encodeByAES56(rk, b);

console.log(eb);

출력 결과는 다음과 같습니다.

mXK9nlcT70QdTjKgzxAD99zS4UYah0OZI8GFT8Pg+Vu3GFmF/HPmlV0PA/sUy7rr4+2Sh319ZEIz2TlyiPWcvw==

암호화된 위의 문자열을 복호화하는 함수는 다음과 같습니다.

decodeByAES256(key, data){
    const cipher = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(""),
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
    });

    return cipher.toString(CryptoJS.enc.Utf8);
};

위의 함수를 사용하는 예는 다음과 같구요.

const k = "key"; // 암호화에서 사용한 값과 동일하게 해야함
const rk = k.padEnd(32, " "); // AES256은 key 길이가 32자여야 함
const eb = "mXK9nlcT70QdTjKgzxAD99zS4UYah0OZI8GFT8Pg+Vu3GFmF/HPmlV0PA/sUy7rr4+2Sh319ZEIz2TlyiPWcvw==";
const b = this.decodeByAES56(rk, eb);

console.log(b);

실행 결과는 다음과 같습니다.

암호화는 보안을 위해 매우 중요합니다.

주말에 THREE.JS를 이용해 만든 것

제 유튜브 채널을 통해 강좌로 소개할 것들에 대해 먼저 결과 만을 찍어 먼저 올려 봅니다. 아마 바로 돌아오는 이번주 토요일 쯤.. 아래 2개 중 한 개를 찍어 올릴 듯 합니다.

제 유튜브 채널 이름은 GIS Developer 입니다. 채널을 구독하시면 영상 업로드 시 바로 알 수 있습니다.