정규표현식: 문자열을 검색하고 대체하는 데 사용 가능한 일종의 형식 언어 패턴,

간단한 문자 검색부터 이메일, 패스워드 검사 등의 복잡한 문자 일치 기능 등을 정규식 패턴으로 빠르게 수행 할 수 있다. 단, 정규식 패턴이 수행 내용과 매치가 잘 안 되어 가독성이 많이 떨어지기 때문에 입문자들이 어려워 하는 경우가 많다. 하지만 초반 개념만 잘 잡으면 금방 익숙해 질 수 있다.

정규표현식 역할

  • 문자 검색(search)
  • 문자 대체(replace)
  • 문자 추출(extract)

정규표현식 테스트 사이트

https://regex101.com/
https://regexr.com/
https://regexper.com/

 

regex101: build, test, and debug regex

Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java. Features a regex quiz & library.

regex101.com

 

자바스크립트 정규식 생성

생성자 함수 방식

RegExp: 생성자 함수를 호출하여 사용할 수 있다.

const regexp1 = new RegExp("^abc")
// new RegExp(표현식)

const regexp2 = new RegExp("^abc", "gi")
// new RegExp(표현식, 플래그)

 

리터럴 방식

정규표현식은 / 로 감싸진 패턴을 리터럴로 사용한다.

const regexp1 = /^abc/;
// /표현식/

const regexp2 = /^abc/gi
// 표현식/플래그

 

예제

// 정규표현식
const str = `
010-1234-5678
hello@gmail.com;
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`
// 대소문자 따져서 검색
// 생성자 방식
// const regexp = new RegExp('the', 'g')
// 리터럴 방식
const regexp = /the/g
console.log(str.match(regexp))

// 대소문자 안가리고 검색
// 생성자 방식
// const regexp2 = new RegExp('the', 'gi')
// 리터럴 방식
const regexp2 = /the/gi
console.log(str.match(regexp2))

'프론트엔드 > JavaScript' 카테고리의 다른 글

정규표현식3 - 플래그(옵션)  (0) 2021.06.07
정규표현식2 - 메소드  (0) 2021.06.07
JS 데이터 - OMDB API  (0) 2021.06.05
JS 데이터 - Storage  (0) 2021.06.04
JS 데이터 - JSON  (0) 2021.06.03

OMDB API: 영화정보를 가져오는 API

 

참고 (검색: omdbapi)

https://www.omdbapi.com/

 

OMDb API - The Open Movie Database

 

www.omdbapi.com

 

영화정보를 요청할 수 있는 URL (api key를 발급 받아야 사용 가능)

Query String: 문자를 가지고 어떠한 정보를 검색한다는 의미

문법: 주소?속성=값&속성=값&속성=값

예시(JSON 형태로 보여진다.)

http://www.omdbapi.com/?apikey=7035c60c&s=frozen

axios: 위와 같은 데이터를 처리해줄수 있는 패키지

https://github.com/axios/axios

 

axios/axios

Promise based HTTP client for the browser and node.js - axios/axios

github.com

HTTP 요청을 처리해줄 수 있는 패키지(브라우저, node.js 환경에서 사용 가능)

 

프로젝트에 설치: npm install axios

package.json 파일에서 확인

실습 코드

// omdb api
// axios 패키지 사용(HTTP 요청을 처리하기 위해)
import axios from 'axios'
function fetchMovies() {
  // apikey= 발급받은 api key, s= 검색하고자 하는 영화 제목
  axios
    .get('https://www.omdbapi.com/?apikey=7035c60c&s=frozen')
    // url에 해당하는 정보를 처리하는 구문
    .then((response) => {
      console.log(response)
    })
}
// 실행
fetchMovies()

응답받은 데이터를 콘솔에서 확인

 

 

index.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script defer src="./main.js"></script>
    <script src="./test.js"></script>
</head>
<body>
    <h1>Hello world !</h1>
    <img src="" alt="" width="200">
</body>
</html>

main.js

// omdb api
// axios 패키지 사용(HTTP 요청을 처리하기 위해)
import axios from 'axios'
function fetchMovies() {
  // apikey= 발급받은 api key, s= 검색하고자 하는 영화 제목
  axios
    .get('https://www.omdbapi.com/?apikey=7035c60c&s=frozen')
    // url에 해당하는 정보를 처리하는 구문
    .then((res) => {
      console.log(res)
      const h1El = document.querySelector('h1')
      const imgEl = document.querySelector('img')
      h1El.textContent = res.data.Search[0].Tilte
      imgEl.src = res.data.Search[0].Poster
    })
}
// 실행
fetchMovies()

'프론트엔드 > JavaScript' 카테고리의 다른 글

정규표현식2 - 메소드  (0) 2021.06.07
정규 표현식  (0) 2021.06.07
JS 데이터 - Storage  (0) 2021.06.04
JS 데이터 - JSON  (0) 2021.06.03
JS 데이터 - lodash 사용  (0) 2021.06.03

Storage: 데이터를 저장하고 있는 공간

 

확인 방법: 개발자 도구 -> 응용  프로그램 -> 저장소 탭에서 확인 가능

 

로컬 저장소(검색: local storage mdn)

https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage

 

Window.localStorage - Web API | MDN

localStorage 읽기 전용 속성을 사용하면 Document 출처의 Storage 객체에 접근할 수 있습니다. 저장한 데이터는 브라우저 세션 간에 공유됩니다.

developer.mozilla.org

 

 

예제

 

저장소에 데이터 저장(value가 Object로 나온다)

// 저장소에 데이터 저장
localStorage.setItem('user', user)

 

저장소에 문자데이터 형태로 저장

// 문자 데이터로 저장
localStorage.setItem('user2', JSON.stringify(user))

 

로컬 저장소 데이터 가져오기(Json 형태로 보여진다)

// 로컬 저장소에서 데이터 가져오기
console.log(localStorage.getItem('user2'))

 

객체 데이터로 변환하여 콘솔에 출력

console.log(JSON.parse(localStorage.getItem('user2')))

로컬저장소에 데이터를 수정하는 방법

// 해당 데이터를 로컬 저장소에 저장시킨다
const str = localStorage.getItem('user2')
// 저장된 데이터를 객체 데이터로 변환
const obj = JSON.parse(str)
// 객체데이터로 변환된 데이터를 수정
obj.age = 22
// 확인
console.log(obj)
// 원래 형태인 문자데이터 형태로 변환
localStorage.setItem('user2', JSON.stringify(obj))

 

로컬 저장소 데이터 제거하는 방법

// 로컬저장소에 데이터를 제거
localStorage.removeItem('user2')

 

Node.js환경에서 lodash 패키지를 이용하여 쉽게 사용 가능하다고 한다(검색: low db)

https://github.com/typicode/lowdb

 

typicode/lowdb

Tiny local JSON database for small projects (supports Node, Electron and the browser) - typicode/lowdb

github.com

참고

DATABASE2 - lowdb - YouTube

 

DATABASE2 - lowdb

 

www.youtube.com

 

'프론트엔드 > JavaScript' 카테고리의 다른 글

정규 표현식  (0) 2021.06.07
JS 데이터 - OMDB API  (0) 2021.06.05
JS 데이터 - JSON  (0) 2021.06.03
JS 데이터 - lodash 사용  (0) 2021.06.03
JS 데이터 - 가져오기, 내보내기  (0) 2021.06.03

JSON

인터넷에서 자료를 주고 받을 때 그 자료를 표현하는 방법으로 알려져 있다. 자료의 종류에 큰 제한은 없으며, 특히 컴퓨터 프로그램 변수값을 표현하는 데 적합하다.

https://ko.wikipedia.org/wiki/JSON

 

JSON - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. JSON(제이슨[1], JavaScript Object Notation)은 속성-값 쌍( attribute–value pairs and array data types (or any other serializable value)) 또는 "키-값 쌍"으로 이루어진 데이터 오브젝트를

ko.wikipedia.org

 

하나의 문자 데이터

import되어지면 객체데이터로 출력된다.

 

JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환

JSON.parse() 메서드는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성

// JSON 
// 자바스크립트의 객체 표기법
// json 파일 가져오기
import myData from './myData.json'
console.log(myData)

const user = {
  name: 'happy',
  age: 89,
  email: [
    'ttt@naver.com',
    'eee@naver.com'
  ]
}
console.log('user', user)

// json형식 (문자데이터)으로 변환
const str = JSON.stringify(user)
console.log('str', str)
console.log(typeof str)

// 자바스크립트에서 해석되는 객체로 저장
const obj = JSON.parse(str)
console.log('obj', obj)

참고 사이트

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON

 

JSON - JavaScript | MDN

JSON 객체는 JavaScript Object Notation(JSON)을 분석하거나 값을 JSON으로 변환하는 메서드를 가지고 있습니다. JSON을 직접 호출하거나 인스턴스를 생성할 수 없으며, 두 개의 메서드를 제외하면 자신만

developer.mozilla.org

 

'프론트엔드 > JavaScript' 카테고리의 다른 글

JS 데이터 - OMDB API  (0) 2021.06.05
JS 데이터 - Storage  (0) 2021.06.04
JS 데이터 - lodash 사용  (0) 2021.06.03
JS 데이터 - 가져오기, 내보내기  (0) 2021.06.03
JS 데이터 - 복사  (0) 2021.06.01

lodash 사이트

https://lodash.com/

 

Lodash

_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn

lodash.com

lodash import

// lodash 사용법
//  선언
import _ from 'lodash'

예제

const userA = [
  { userId: '1', name: 'happy'},
  { userId: '2', name: 'neo'}
]
const userB = [
  { userId: '1', name: 'happy1'},
  { userId: '3', name: 'amy'}
]

concat 함수: 원하는 객체의 데이터들을 합쳐서 저장

 

// userA에 userB 데이터를 합쳐서 userC에 저장
const userC = userA.concat(userB)
console.log('concat', userC)

 

uniqBy 함수: 중복값을 제거하는 함수(뒤에 나오는 데이터를 제거 한다.)

// userId의 중복 값을 제거 (뒤에 데이터를 제거 한다.)
console.log('uniqBy', _.uniqBy(userC, 'userId'))

 

unionBy 함수: 중복없이 데이터를 합치는 함수

// userId의 중복 없이 userA, userB 데이터를 합쳐서 userD에 저장
const userD = _.unionBy(userA, userB, 'userId')
console.log('unionBy', userD)

 

 

예제

const users = [
  { userId: '1', name: 'happy'},
  { userId: '2', name: 'neo'},
  { userId: '3', name: 'evan'},
  { userId: '4', name: 'lea'},
  { userId: '5', name: 'yaa'}
]

find 함수: 특정 데이터를 찾아서 보여주는 함수

// users라는 배열 데이터에서 name값이 evan인 데이터를 찾는다.
const foundUser = _.find(users, {name: 'evan'})
console.log(foundUser)

findIndex 함수: 특정 데이터의 index 값을 반환해주는 함수

// users라는 배열 데이터에서 name값이 evan인 index 번호를 찾는다. 0부터 시작
const foundUserIndex = _.findIndex(users, {name: 'evan'})
console.log(foundUserIndex)

remove 함수: 특정 데이터를 제거해주는 함수

// users라는 배열 데이터에서 name 값이 happy인 데이터를 제거한다.
_.remove(users, {name: 'happy'})
console.log(users)

'프론트엔드 > JavaScript' 카테고리의 다른 글

JS 데이터 - Storage  (0) 2021.06.04
JS 데이터 - JSON  (0) 2021.06.03
JS 데이터 - 가져오기, 내보내기  (0) 2021.06.03
JS 데이터 - 복사  (0) 2021.06.01
JS 데이터 - 불변성  (0) 2021.06.01

외부에 있는 js 파일을 내보내기: export

기본 통로로 내보내는 예제

// 외부에서도 사용가능하도록 설정 export default 
// 이름을 없애도 되고 import에서 사용자가 원하는 이름으로 불러올수 있다.
export default function getType(data) {
    return Object.prototype.toString.call(data).slice(8, -1)
}

module 통로로 내보내는 예제(하나의 js 파일에서 여러개의 함수를 내보낼수 있다.)

export function random () {
    // 랜덤값을 얻어온 다음에 소수점 밑에 자리를 버린다
    return Math.floor(Math.random() *10)
}

export const user = {
    name: 'happy',
    age: 90
}

 

외부에 있는 파일 가져오기: import

예제

default로 내보낸 함수를 받는 방법

import _ from 'lodash'  // From 'node_modules' !
import getType from './getType' // getType.js
import getRandom from './getRandom' // getRandom.js

모듈로 내보낸 함수를 받는 방법(여러개 가능): 중괄호 { } 사용

import {random, user as happy} from './getRandom'

as 키워드로 이름을 바꿔서 사용 가능

 

모든 export 파일을 가져오는 방법(default를 혼용해서 모두 가져올 수 있다.)

import * as R from './getRandom'

확인

console.log(R)
console.log(R.random())

'프론트엔드 > JavaScript' 카테고리의 다른 글

JS 데이터 - JSON  (0) 2021.06.03
JS 데이터 - lodash 사용  (0) 2021.06.03
JS 데이터 - 복사  (0) 2021.06.01
JS 데이터 - 불변성  (0) 2021.06.01
JS 데이터 - 전개 연산자 (Spread)  (0) 2021.05.31

+ Recent posts