본문 바로가기
IT/Javascript

문자열 다루기

by DOSGamer 2022. 7. 13.
반응형

문제

문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.

제한조건

  • s는 길이 1 이상, 길이 8 이하인 문자열입니다.

풀이방향

  • 입력 문자열의 길이가 4, 6 인지 확인
  • 입력 문자열이 숫자로 구성되었는지 확인

문제풀이

function handlingString(s) {
  let answer = true;
  //문자열의 길이가 4, 6 이 아닌지 확인
  if (s.length !== 4 && s.length !== 6) {
    answer = false;
  }
  //문자가 숫자로만 구성되어있는지 확인
  for (let i = 0; i < s.length; i++) {
    if (s[i] < "0" || s[i] > "9") {
      answer = false;
    }
  }
  return answer;
}

export { handlingString };
import { handlingString } from "../src/handlingString";

describe("handlingString", () => {
  it("should return false if the length of the string is not 4 or 6", () => {
    expect(handlingString("Jane")).toBe(false);
    expect(handlingString("JaneKim")).toBe(false);
  });

  it("should return false if the string contains non-numeric characters", () => {
    expect(handlingString("Jan123")).toBe(false);
    expect(handlingString("J123")).toBe(false);
  });

  it("should return true if the string is composed of numeric characters", () => {
    expect(handlingString("1234")).toBe(true);
    expect(handlingString("123456")).toBe(true);
  });
});

문제출처

다른 풀이

function alpha_string46(s){
  var regex = /^\d{6}$|^\d{4}$/;
  return regex.test(s);
}
반응형

'IT > Javascript' 카테고리의 다른 글

x만큼 간격이 있는 n개의 숫자  (0) 2022.07.13
정수제곱근 판별  (0) 2022.07.13
핸드폰 번호가리기  (0) 2022.07.13
하샤드 수  (0) 2022.07.13
최대공약수와 최소공배수  (0) 2022.07.13
가운데 글자 가져오기  (0) 2022.07.13
평균구하기  (0) 2022.07.13
나머지가 1이 되는 수 찾기  (0) 2022.07.12