문자열 관련 함수

JIY00N·2023년 4월 4일
0

HTML / CSS / JavaScript

목록 보기
17/18
post-thumbnail

2023.04.04

  1. Set
// 1. 배열 중복 삭제
const arr = [1,2,2,2,3,3,4];
const mySet = new Set(arr);
mySet.has(1); // true
mySet.has(0); // false
console.log([...mySet]); // [1,2,3,4]
// 2. 원소의 수를 나타냄
const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add("some text");
mySet.add(1);
mySet.size; // 3
  1. charAt - 해당 index 문자열 반환
    구문: str.charAt(index)
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.charAt(0)); // T
  1. substring - 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환
    구문: str.substring(indexStart[, indexEnd])
const str = 'Mozilla';
console.log(str.substring(1, 3)); // oz
console.log(str.substring(2)); // zilla
  1. indexOf - string 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환, 없으면 -1 반환
    💡 indexOf를 사용하여 문자열 내의 특정 문자 숫자 세기
const s = "110010101001";
let str = s.indexOf("1");
let cnt = 0;
while(str !== -1){
  cnt++;
  str = s.indexOf("1", str+1);
}
console.log(cnt); //6
  1. toString - 진수 변환
const s = 6
const ans = s.toString(2);
console.log(ans); // "110"
  1. repeat - 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환
    구문: str.repeat(count);
//예제1
'abc'.repeat(2); // 'abcabc'
//예제2
let answer = '';
for(let i = 0; i < 10; i++){
  answer += String(i).repeat(1);
}
console.log(answer); //0123456789
  1. Math.max, Math.min이 문자열도 취급
profile
블로그 이전 했습니다. https://yoon-log.vercel.app/

0개의 댓글