20210520 JavaSciprt 05 : Storage, OMDb API, Query String, Axios, 정규표현식

6 분 소요

JavaScript05

Javascript : Storage

  • key - value 형태의 데이터 저장소
  • Local Storage
    • : Document 출처의 Storage객체에 접근, 도메인 주소(사이트)에 종속되어 저장
    • 데이터 만료되지 않음, 반영구적 보존
  • Session Storage
    • : 페이지 세션이 끝날 때(페이지를 닫을 때 사라 짐)


localStorage 데이터 활용

  • setItem(key: string, value: string)

    • 문자 데이터만 받기 때문에 문자데이터가 아닌 경우는 JSON을 통해 stringify를 통해서 문자로 저장하고
    • 활용시에는 parse로 살려서 활용


  • getItem(key: string)
  • removeItem(key: string) (이렇게 하지 않는 이상 지워지지 않음)


const user = {
  name: "Tom",
  age: 25,
  emails: ["BraveGirls@gmail.com", "Tom@gmail.com"],
};

// 추가하기
localStorage.setItem("user", JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem(`user`)));
localStorage.removeItem("user");

// 수정하기
const str = localStorage.getItem("user");
const obj = JSON.parse(str);
obj.age = 22;
console.log(obj);
localStorage.setItem("user", JSON.stringify(obj)); // 수정은 덮어쓰기 형식으로 해야함
  • 위처럼 localStorage를 코드로 관리하기가 힘든데 이를 편하게 만들어주는 API가 있음
  • lowdb API




Javascript : OMDb API, Query String, Axios

  • OMDb API : 영화 정보 검색 restful web site

    • 영화 정보를 query string을 통해서 JSON 형식의 데이터를 웹에 표현함
  • Query String : 주소?속성=값&속성=값&속성=값 형태로 ? 다음에 오는 옵션에 따라 페이지가 조금씩 달라지게 하는 주소 포맷

  • Axios : 해당 주소의 데이터를 요청할 수 있는 프로미스 기반의 HTTP Client 통신 라이브러리

// API key 필요
import axios from "axios";

function fetchMovies() {
  axios.get("https://www.omdbapi.com/?apikey=0000000&s=frozen").then((res) => {
    console.log(res); // console을 통해서 데이터 구조 확인 가능
    const h1El = document.querySelector("h1");
    const imgEl = document.querySelector("img");
    h1El.textContent = res.data.Search[0].Title;
    // Dom을 이용해서 해당 태그에 title 데이터를 넣음
    imgEl.src = res.data.Search[0].Poster;
    // Dom을 이용해서 해당 태그에 img 데이터를 넣음
  });
}

fetchMovies();




Javascript : 정규 표현식 (RegExp, Regular Expression)

  • regexp by HEROPY Tech
  • regexr.com

  • 정규 표현식 :
    • 문자열을 검색, 대체, 추출하는 데 사용 가능한 일종의 형식 언어(패턴)임
  • 모든 언어에서 사용하지만 언어에 따라 지원하는게 조금 씩 다르기 때문에 사용 환경에 영향을 미침


정규표현식 생성

생성자 함수 방식

  • RegExp 생성자 함수를 호출
  • RegExp('패턴', '검색 방식 옵션')
// 생성자
new RegExp("표현", "옵션");
new RegExp("[a-z]", "gi");
// g 옵션 : 일치하는 모든 내용 검색
// i 옵션 : 대문자 소문자 구분 안하겠다.



리터털 방식

  • /로 감싸진 패턴을 리터럴로 사용
/표현/옵션
/[a-z]/gi



패턴 검색

  • input 데이터에서 검색해서 해당 데이터를 배열데이터로 만들어줌
const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=000000&s=frozen
The quick brown fox jumps over the lazy dog
abbcccdddd
`;

// 생성자 함수 방식
const regexp01 = new RegExp("the", "");
const regexp02 = new RegExp("the", "g");
const regexp03 = new RegExp("the", "gi");

console.log(str.match(regexp01)); // ["the", index: 15, input: "↵010-1234-5678↵thesecon@gmail.com↵https://www.omdb…ick brown fox jumps over the lazy dog↵abbcccdddd↵", groups: undefined]
console.log(str.match(regexp02)); // (2) ["the", "the"]
console.log(str.match(regexp03)); // (3) ["the", "The", "the"]

// 리터럴 방식
const regexp04 = /the/gi;
console.log(str.match(regexp04)); // (3) ["the", "The", "the"]


정규표현식을 사용하는 메소드

  • exec
    • (정규식.exec(문자열)) : 일치하는 하나의 정보(Array) 반환
  • test
    • (정규식.test(문자열)) : 일치 여부(Boolean) 반환
  • match
    • 문자열.match(정규식) : 일치하는 문자열의 배열(Array) 반환
  • search
    • (문자열.search(정규식)) : 일치하는 문자열의 인덱스(Number) 반환
  • replace
    • (문자열.replace(정규식,대체문자)) : 일치하는 문자열을 대체하고 대체된 문자열(String) 반환
  • split
    • (문자열.split(정규식)) : 문자열.split(정규식) 일치하는 문자열을 분할하여 배열(Array)로 반환
  • toString
    • (생성자_정규식.toString()) : 생성자 함수 방식의 정규식을 리터럴 방식의 문자열(String)로 반환
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=000000&s=frozen
The quick brown fox jumps over the lazy dog
abbcccdddd
`;

const regexp01 = /fox/gi;

console.log(regexp01.test(str)); // true
console.log(str.replace(regexp01, "AAA"));
// 010-1234-5678
// thesecon@gmail.com
// https://www.omdbapi.com/?apikey=000000&s=frozen
// The quick brown AAA jumps over the lazy dog
// abbcccdddd
console.log(`원본 손상 X : `, str);
// 원본 손상 X :
// 010-1234-5678
// thesecon@gmail.com
// https://www.omdbapi.com/?apikey=000000&s=frozen
// The quick brown fox jumps over the lazy dog
// abbcccdddd

// 원본 수정하고 싶으면, const 대신 let으로 변수 선언을 바꾸고 replace한 데이터를 받아 원본 변수에 재할당 하면 수정됨
str = str.replace(regexp01, "AAA");

console.log(`재할당 결과 : `, str);
// 재할당 결과 :
// 010-1234-5678
// thesecon@gmail.com
// https://www.omdbapi.com/?apikey=000000&s=frozen
// The quick brown AAA jumps over the lazy dog
// abbcccdddd



플래그 (옵션)

플래그 설명
default (없음) 처음으로 일치하는 문자
g (global) 일치하는 모든 문자
i (ignore case) 영어 대소문자 구분 않고 일치하는 문자
m (multi line) 여러 줄 일치하는 문자 (원래 정규식은 여러줄 고려 X)
let str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`;

// 옵션에 따른 검색

console.log(str.match(/the/));
// ["the", index: 15, input: "↵010-1234-5678↵thesecon@gmail.com↵https://www.omdb…ck brown fox jumps over the lazy dog.↵abbcccdddd↵", groups: undefined]
// 처음으로 찾은 문자, index, input 등의 다양한 정보를 보여줌

console.log(str.match(/the/g));
// (2) ["the", "the"]
// 일치하는 문자 전부 표현

console.log(str.match(/the/gi));
// (3) ["the", "The", "the"]
// 대소문자 구분 안함

console.log(str.match(/\./gi));
// (4) [".", ".", ".", "."]
// 이스케이프 문자(백슬레쉬)를 통해서 일부 특수기호에 적용해서 해당 특수기호 검색 가능

console.log(str.match(/\.$/gi));
// null
// m 옵션이 없으면, start end를 백틱의 시작과 끝 단위로 인식한다. 해당 문자가 끝나는 부분에 `.`이 있는지를 확인함 `$`

console.log(str.match(/\.$/gim));
// ["."]
// m 옵션에 따라서 개행문자를 인식해서 start end를 줄 단위로 인식한다. 또 `$`를 썼기 때문에 한줄 한줄의 끝 부분에 `.` 이 있는지 검색함



패턴 (표현)

패턴 설명
^ab line 시작에 있는 ab와 일치
ab$ line 끝에 있는 ab와 일치
. 임의의 한 문자와 일치 (자리수에 쓰임)
a|b a 또는 b와 일치
ab? b가 없거나 b와 일치
A{3} A라는 문자가 3개 연속 일치 (AAA)
A{3,} A라는 문자가 3개 이상 연속 일치
A{3,5} A라는 문자가 3개 이상 5개 이하 연속 일치
[abc] a 또는 b 또는 c
[a-z] a부터 z 사이의 문자 구간에 일치(영어 소문자)
[A-Z] A부터 Z 사이의 문자 구간에 일치 (영어 대문자)
[0-9] 0부터 9 사이의 무자 구간에 일치 (숫자)
[가-힣] 가부터 힣 사이의 문자 구간에 일치 (한글)
\w 63개 문자 (Word, 대소영문52개 + 숫자10개 + _)에 일치
\b 63개 문자에 일치하지 않는 문자를 경계로 인식(Boundary)
\d 숫자 (Digit)에 일치
\s 공백(Space, Tab 등)에 일치
A(?=k) k문자 앞쪽 A문자 일치 (Lookahead)
(?<>=k)A k문자 뒤쪽 A문자 일치 (Lookbehind)
  • Entity(엔티티) : html에서 기능을 담당하는 기호(HTML 예약어, HTML reserved)의 경우 그대로 표현하고자 하는 경우 대체하여 사용하는 문자셋을 말함


정규표현식 패턴 : ‘$’, ‘^’ (line 끝, 시작 일치)

const str01 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`;

const str02 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
d`;

// line 끝 일치 '$'
console.log(str01.match(/d$/g)); // null (안보이지만 개행 문자도 인식 하기 때문에)

console.log(str02.match(/d$/g)); // ["d"]

console.log(str01.match(/d$/gm)); // ["d"] (m 플래그를 통해서 start end를 줄로 했기 때문에)

// line 시작 일치 '^'
console.log(str01.match(/^t/gm)); // ["t"]
console.log(str01.match(/^T/gm)); // ["T"]
console.log(str01.match(/^t/gim)); // ["t", "T"]
console.log(str01.match(/./g)); // (133) ["0", "1", "0", "-", ...] (들어있는 문자 모두를 일치시켜서 하나 하나 배열로 만듦)


정규표현식 패턴 : ‘.’, ‘|’, ‘?’, ‘{}’

const str03 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
hxyp`;

// 임의 문자 일치 `.`
console.log(str03.match(/h..p/g)); // [http, "hxyp"] 즉, 임의 문자이니까 글자수를 표시할 수 있음

// or 조건 `|`
console.log(str03.match(/fox | dog/g)); // ["fox ", " dog"]

const str04 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
http://localhost:1234`;

// 있거나 없거나 조건 '?'
console.log(str04.match(/https?/g)); // s? -> ["https", "http"]

// 문자의 연속 개수 조건 `{}`
console.log(str04.match(/d{2}/g)); // ["dd", "dd"]
console.log(str04.match(/d{2,}/g)); // ["dddd"]
console.log(str04.match(/d{2,3}/g)); // ["ddd"]


정규표현식 패턴 : ‘\w’, ‘\b’, ‘\d’, ‘\s’, ‘[]’

const str04 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
http://localhost:1234`;

// \w : 영 숫 언더바
console.log(str04.match(/\w{2,3}/g)); // \w : 숫자를 포함한 영어 알파벳 언더바
// ["010", "123", "567", "the", "sec", ... ]

// \b : 숫자, 문자가 아닌 기호
console.log(str04.match(/\b\w{2,3}\b/g));
// ["010", "com", "www", "com", "The", "fox", "the", "dog"]

// []
console.log(str04.match(/[fox]/g)); // f | o | x
console.log(str04.match(/[0-9]{3,}/g)); // (5) ["010", "1234", "5678", "0000000", "1234"]

const str05 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
http://localhost:1234
동해물과_백수산이 마르고 닳도록
`;

console.log(str05.match(/[각-힣]{1,}/g)); // (4) ["동해물과", "백수산이", "마르고", "닳도록"]

console.log(str05.match(/\w/g)); // 영,숫,언더바

console.log(str05.match(/\bf\w{1,}\b/g)); // ["frozen", "fox"]

console.log(str05.match(/\d{1,}/g)); // (5) ["010", "1234", "5678", "0000000", "1234"]

console.log(str05.match(/\s/g)); // 띄어쓰기, 개행문자 (18) ["↵", "↵", "↵", "↵", " ", " ", " ", " ", " ", " ", " ", " ", "↵", "↵", "↵", " ", " ", "↵"]

const h = `  the hello  world   !

`;
console.log(h.replace(/\s/g, "")); // thehelloworld!


정규표현식 패턴 : ‘(?=)’, ‘(?<=)’

// 특정 문자 앞 뒤 검색 (?=), (?<=)
const str01 = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=0000000&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`;
console.log(str01.match(/.{1,}(?=@)/g)); // ["thesecon"]
console.log(str01.match(/(?<=@).{1,}/g)); // ["gmail.com"]