• 코드스테이츠 SEB 3일차 TIL - JS 문자열, Checkpoint

    2021. 7. 21.

    by. 자율학습 코딩봇

    3일차 일정을 끝내고 다시 블로그에 글을 쓰려고 보니 어제자의 텍스트 일부분이 묘하게 깨져있는 걸 확인했다.
    이게 왜 저렇게 표시되지...?

    그래서 오늘은 기본모드에서 작성하던걸 그냥 마크다운으로 작성하끔 바꾸려고 시도는 해봤다.... ㅎ
    아무리 해봐도 무언가 티스토리의 마크다운 적용이 이상한 것 같아서 포기했다.
    글 쓰는 거 내용도 아니고 생긴 것 까지 그렇게 신경쓰고 싶지 않아...

     



    오늘을 약간 되짚어보면 사실 강의를 많이 들으면서 뭔갈 많이 배웠다기 보다는 거의 어제 배운 것들을 확인 해보는 날이었다.
    코플릿으로 문제 20개 넘게 풀어본듯;; 뭔가 기가 잔뜩 빨린 것 같은데 그래도 TIL은 써야하기에 배운 내용을 다시 정리해본다.

     


    문자열 - Achivement Goal

    문자 챕터에서는 대부분의 달성 목표들이 method였다.

     

    • 문자열의 속성과 메소드를 이용해 원하는 형태로 만들 수 있다.
    • 문자열의 length라는 속성을 활용해 길이를 확인할 수 있다. str.length
    let str = 'hello world'
    console.log(str.length) // => 10
    • 문자열의 글자 하나하나에 접근할 수 있다. str[1]

    index로 접근은 가능하지만 수정은 불가능함 (Read-Only)

    var str = 'CodeStates'; str[0] = 'G'; console.log(str); // 'CodeStates' not 'GodeStates'
    • 문자열을 합칠 수 있다. word1 + " " + word2
    • 문자열을 원하는 만큼만 선택할 수 있다. str.slice(0, 3) 또는 str.substring(0, 3)

    여기서는 slice와 substling의 차이가 무엇인지 궁금해서 검색을 해봤다.

    stackoverflow에서 그 답을 알 수 있었는데 아래와 같이 원문을 가져왔다.

     

    참조 : https://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring

    What they have in common:
    1. If start equals stop: returns an empty string
    2. If stop is omitted: extracts characters to the end of the string
    3. If either argument is greater than the string's length, the string's length will be used instead.

    Distinctions of substring():
    1. If start > stop, then substring will swap those 2 arguments.
    2. If either argument is negative or is NaN, it is treated as if it were 0.

    Distinctions of slice():
    1. If start > stop, slice() will return the empty string. ("")
    2. If start is negative: sets char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
    3. If stop is negative: sets stop to: string.length – Math.abs(stop) (original value), except bounded at 0 (thus, Math.max(0, string.length + stop)) as covered in the ECMA specification.

    slice의 차이점 3번을 보다가 Math 내장 객체에 대해서도 학습하게 되었다.

    요부분은 mdn에서 충분히 확인이 가능할 듯하여 mdn에서 찾아보았다.

    (Math.max는 딱 봐도 최댓값 뽑는 듯해서 콘솔로 써봐서 그 기능이 맞았기에 따로 검색은 하지 않았다.)

    Math.abs()
    The Math.abs() function returns the absolute value of a number. That is, it returns x if x is positive or zero, and the negation of x if x is negative.

    결론적으로 입력되는 것을 절댓값으로 바꿔주는 듯 하다. 그리고 입력되는 형태별로 다른 결과값이 나오는 경우가 있다고 예시가 있었는데
    그 부분은 아래 정리해두었다.

    Math.abs('-1');     // 1
    Math.abs(-2);       // 2
    Math.abs(null);     // 0
    Math.abs('');       // 0
    Math.abs([]);       // 0
    Math.abs([2]);      // 2
    Math.abs([1,2]);    // NaN
    Math.abs({});       // NaN
    Math.abs('string'); // NaN
    Math.abs();         // NaN

     

    • 영문을 모두 대문자로 바꿀 수 있다. str.toUpperCase()
    • 영문을 모두 소문자로 바꿀 수 있다. str.toLowerCase()
    • 문자열 중 원하는 문자의 index를 찾을 수 있다 str.indexOf('a') 또는 str.lastIndexOf('a')

    indexOf : 문자열의 좌측부터 처음 발견되는 문자의 위치를 반환

    lastIndexOf : 문자열의 우측부터 처음 발견되는 문자의 위치를 반환

    (딱 이름부터 반대 기능하는 것처럼  생겼다.)

    • 문자열 중 원하는 문자가 포함되어 있는지 알 수 있다. str.includes('a')

    Advanced Challanges

    • 띄어쓰기 (" ") 로 문자열을 구분하여 배열로 바꿀 수 있다. str.split(" ")
    • 위의 배열의 요소 사이에 띄어쓰기 (" ") 넣어 다시 문자열로 바꿀 수 있다. str.split(" ").join(" ")

    +  추가 학습 내용

    챕터에서 제시된 내용 외 오늘 개인적으로 학습하게 되었던 부분들을 복습해본다.
    오늘 추가학습한 내용은 모두 method여서 MDN에서 관련 내용을 긁어와서 학습했다.

    • parseInt()
      The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
      간단히 생각하면 문자열 숫자에서 number 타입의 정수를 반환하는 듯하다.
    • parseFloat()
      The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.
      문자열에서 소수점이 포함된 number 타입의 실수를 반환한다.
    • Math.PI
      The Math.PI property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159:
      parseFloat에 대한 Demo를 보다가 안에 있어서 검색해봤는데 역시 원주율(pi) 값을 뽑아내준다. 매개변수가 없다.
    • String.prototype.trim()
      The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
    • String.prototype.match()
      The match() method retrieves the result of matching a string against a regular expression.

      괄호안 매개변수 부분을 정규표현식으로 받아서 그에 대응하는 결과값을 출력한다는 이야기인데 흥미롭게도 여기서 받아지는 regexp와 관련한 내용이 더 있어서 아래 붙인다.

      regexp
      A regular expression object.
      If regexp is a non-RegExp object, it is implicitly converted to a RegExp by using new RegExp(regexp).
      If you don't give any parameter and use the match() method directly, you will get an Array with an empty string: [""].

    • String.prototype.replace()
      The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.

    string 관련된 method에서 정규 표현식 반영되는 구석이 다소 있어서 재미있게 느껴진다.

    정규표현식에 관해서는 일부 기능에 한정해서 쓸줄 알지만 이번 기회에 제대로 더 배우면 좋을 듯하다.

    (이것도 주말에...)


    3일차에는 아침부터 페어로 조건문 코플릿 문제 풀기를 하였고, 오후 타임에는 문자열 챕터 학습, 그리고 또 문자열 코플릿 풀기

    그리고 바로 어제부터 배운 변수~문자열의 체크포인트 문제 풀이를 하였다.

    그러다보니 상단에서 말한 것과 같이 따로 더 학습을 진행하거나 한 부분은 없어서 위와 같이 학습한 범위의 성과 목표가 어제보다는 적었다.

     

    스케줄을 보니 내일부터는 반복문 코플릿을 5시간 동안 푼다.... wow

    일단 오늘 자면서 부디 별일 없길 기도 해야겠다.

     

     

    댓글