본문 바로가기
js

"String " ( split, slice )

by 땅빵주 2021. 2. 7.

  1. split() 

string 객체를 여러개의 문자열로 나눌 수 있다 .

const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);  // "fox 

 

단어도 쪼갤 수 있다.

 

let str = "abcdefg"

let word = str.split('')

console.log(word);


//[ a, b, c, d, e, f, g ]

 

주의해야할 점은 split은 빈 문바열이 주어졌을 때 빈 문자열을 포함한 배열을 반환한다.

const word = "";

const split = word.split();

console.log(split); 

// [" "];

 

2.slice 

배열의 시작부터 end(미포함)에 대해 새로운 배열 객체로 반환한다

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(1,5));  ///   ['bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(3));    ///   ['duck', 'elephant'];

 

3. indexOf( ) 

지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('duck'));

///3

 

'js' 카테고리의 다른 글

Instagram 로그인버튼 색 바꾸기  (0) 2021.01.24
배열조작하기 (push,unshift,pop)  (0) 2021.01.24
반복문 - for문  (0) 2021.01.19
객체(Object)  (0) 2021.01.05
공부하면서 궁금한점 끄적이는 페이지.  (0) 2020.12.29

댓글