프론트엔드 스쿨 5기 TIL - 3월 30일 (2) - string 메서드

크롱·2023년 3월 31일
0

JavaSrcipt

목록 보기
7/53

🌈 string 메서드

.indexOf .search .replace .slice .substring .includes .split .trim padStart

📌 .indexOf

  • .indexOf : 동일한 값이 2개 이상있을 경우엔 무조건 제일 앞에 위치한 값을 반환
<script>
 let txt = 'hello'
 txt.indexOf('l') // 2 반환. 3번째 l은 어떻게 반환하지?
 txt.lastIndexOf('l') // 3 
</script>

또한 .indexOf 는 인자값을 두개를 받을 수 있다.
https://bomango.tistory.com/46 이 블로그를 참고했다.
.indexOf(찾는 값, 시작점)
array = ['min', 'hope', 'jin', 'kok', 'hope'];

알아둬야할 점: 시작점이 검색해야할 값보다 클 경우, (예를 들면 'min'(0번째)을 검색해야하는데 시작점을 2로 설정하면) 검색이 안되므로 무조건 -1을 반환한다.

<script>
.indexOf(찾는 값, 시작점)
array = ['min', 'hope', 'jin', 'kok', 'hope'];

array.indexOf('jin', 1);  // 2
array.indexOf('hope', 3);  // 4를 반환. 
//3번째 'kok' 이 시작점이니 찾는 방향 왼->오 로 인해 4번째 'hope'의 index를 반환.

</script>

만약 시작점에 음수가 온다면?


배열 가장 끝 값: -1
왼쪽으로 갈수록 시작점도 작아진다.

<script>
array.indexOf('jin', -1);  // -1;
array.indexOf('jin', -2);  // -1;
//-1이 시작점이므로 'hope'에서 'jin'을 검색한다. 그런데 검색은 왼->오른쪽 
//'hope' 다음에는 'jin'은 찾을 수 없다.. 따라서 값은 -1이 반환된다.

//-2가 시작점으로 와도  -2는 'kok'인데 'kok' 다음에는 'jin'이 검색되지 않으므로 -1이 반환된다.

//자기 자신인 -3 부터 그 이하의 값들은 시작점에 상관없이 무조건 'jin'의 원래 인덱스값을 반환한다.
array.indexOf('jin', -3);  // 2;
array.indexOf('jin', -4);  // 2;
array.indexOf('jin', -5);  // 2;

</script>

몇번째에 위치하는지 알려줍니다.

일정한 패턴을 찾고 싶다면?

<script>
let txt = 'abhehe'
let pattern = /he/       // he 패턴찾으셈
txt.search(pattern)     // 2

let pat = /bh/
txt.search(pat)        // 1
</script>

대문자를 찾고 싶다면?

<script>
	let txt = 'abcHello'
    let Big = /[A-Z]/g
    console.log(txt.search(Big)) // 3
</script>

📌 .replace(a,b)

a를 b로 바꿔조

<script>
 let sayHello = 'hello'
 console.log(sayHello.replace('he','ha')) // hallo
</script>

📌 .slice 와 .substring

<script>
let txt = 'abcd'

txt.slice(1,3) // 'bc'
txt.substring(1,3) // 'bc'

txt.slice(1,0) // 공백뜸
txt.substring(1,0) // 'a', substring(0, 1)로 처리

txt.slice(1,-2) // 'b'
txt.substring(1,-2) // 'a' , 음수값을 0으로 인식.
</script>

📌 .includes

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별

<script>
const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// true
console.log(pets.includes('at'));
//  false

const txt = 'abcd'
console.log(txt.includes('a')) //true
</script>

📌 .split

<script>
	let text1 = 'aa bb cc dd'
	let text2 = 'aa-bb-cc-dd'
	let text3 = 'aa,bb,cc,dd'
	let text4 = 'aa,bb-cc-dd' /
	 // split 으로  ['aa', 'bb', 'cc', 'dd'] 를 만들어보자
 
	console.log(text1.split(' '))
	console.log(text2.split('-'))
	console.log(text3.split(',')) 
	console.log(text4.replace(',', '-').split('-'))
	console.log(text4.split(/[,-]/g))
</script>

📌 공백을 제거하는 trim

<script>
let text = '                  hi       '
text.trim()  // 'hi'

또 다르게 공백을 제거하고 싶다면 text.replaceAll(' ', '')
</script>

📌 padStart

<script>
	let str1 = '99'
	console.log(str1.padStart(5, '0'));  // 00099반환
</script>
profile
👩‍💻안녕하세요🌞

0개의 댓글