[js] 문자열 연습하기(includes/substr/replace)

전상욱·2021년 5월 24일
0

js & ts 

목록 보기
9/12

includes

  • 지정된 문자열의 포함 여부를 확인하고 싶을때.
  • 입력폼의 부적절한 문자를 체크하고 싶을때

문자열.includes(검색대상문자열,[검색시작인덱스])
ex)

const ex = 'javascript 잘하고 싶다'
const result = ex.include('javascript')
console.log(result) //true 

substr(시작인덱스, 글자수)

  • 위치와 글자 수를 지정한 문자열을 추출하고 싶을때.

두번째 인수에 추출하고 싶은 글자 수를 지정한다. 인덱스 위치와 글자 수를 지정하여 필요한 위치부터 원하는 길이만큼의 문자열을 추출한다.

'javascript'.substr(4, 6) //script

replace(문자열1, 문자열2) / replace(정규표헌, 문자열)

  • 문자열을 다른 문자열로 바꾸고 싶을때
  • 빈칸을 제거 하고 싶을때 등등
const imageName = "image1.png";
const result = imageName.replace("image1.png", "image2.png");
console.log(result);
// image2.png
let phoneNumber = '010-2322-3232'
const result = phoneNumber.replace(/-/g, '')
console.log(result)
//01023223232 

정규 표현식으로 특정 문자 검색하기

  • 조건과 일치하는 문자열 검색하고 싶을때 ( ex) 전화번호 검색)
  • /패턴/.test(문자열) : 문자열과 패턴의 일치 여부 확인

html


<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="/src/styles.css" />
  </head>
  <body>
    <input
      type="tel"
      name="phone-number"
      id="phone-number"
      placeholder="전화번호를 입력해주세요"
    />
    <button id="send">데이터전송</button>
    <p id="warning"></p>
    <script src="./src/index.js"></script>
  </body>
</html>

javascript

  • 정규표현식으로 0으로 시작하는 10자리 혹은 11 자리의 번호형식 체크
  • replace 로 '-'제거
const phoneNumber = document.querySelector("#phone-number");
const warning = document.querySelector("#warning");
document.querySelector("#send").addEventListener("click", (event) => {
  const phoneValue = phoneNumber.value;
  const result = phoneValue.replace(/-/g, "");

  if (/^[0][0-9]{9,10}$/.test(result) === false) {
    warning.innerText = "전화번호 형식에 맞춰 입력해 주세요";
  } else {
    warning.innerText = `${result}`;
  }
  event.preventDefault();
});
profile
someone's opinion of you does not have to become your reality

0개의 댓글