
String의 메소드 아는거 말고 내가 몰랐던것들 정리!!
String.at()이란? 문자열 index에 위치한 문자를 추출해준다.
const sentence = 'The quick brown fox jumps over the lazy dog.';
let index = 5;
console.log(`An index of ${index} returns the character ${sentence.at(index)}`);
// Expected output: "An index of 5 returns the character u"
// 5번째에 위치한 문자는 u 앞 0번째부터 시작한다.
index = -4;
console.log(`An index of ${index} returns the character ${sentence.at(index)}`);
// Expected output: "An index of -4 returns the character d"
// -4면 뒤에서부터 4번째에 위치한 문자는 d 얘는 뒤 1번째부터 시작한다.
at()은 charAt()과 다르게 음수값을 받아 뒤에서 부터 -n 인덱스의 문자를 추출해준다. at()은 ECMAScript2021이상에서만 쓸 수 있다.
This method allows for positive and negative integers. Negative integers count back from the last string character.
[출처] MDN String.prototype.at()
String.charAt()이란 ? 문자열 index에 위치한 문자를 추출해준다. 근데 역으로 찾아주진 않는다.
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"
String.concat(string[])이란? 하나 이상의 문자열을 합쳐서 새로운 문자열을 반환한다. 기존 문자열을 변경하지 않고 새로운 문자열을 생성한다.
const newString = str.concat(string1, string2, ..., stringN);
const str1 = 'Hello';
const str2 = 'World';
const result = str1.concat(', ', str2, '!');
console.log(result); // 출력: Hello, World!
str1.concat(', ', str2, '!')은 'Hello'와 ', ', 'World', '!'를 합쳐서 새로운 문자열 'Hello, World!'를 생성합니다.
기존의 str1과 str2는 변경되지 않고 그대로 유지됩니다.
concat() 메서드는 문자열을 합치는 간편하고 유용한 방법이며, 여러 문자열을 하나로 합치는 작업에 자주 사용됩니다.
String.indexOf()란? 주어진 문자열에서 특정 부분 문자열의 첫 번째 등장하는 인덱스를 반환합니다. 해당 부분 문자열이 없으면 -1을 반환합니다.
const index = str.indexOf(searchValue, startIndex);
const str = 'Hello, World!';
const index1 = str.indexOf('o'); // 'o'의 첫 번째 등장 인덱스를 찾음
console.log(index1); // 출력: 4
const index2 = str.indexOf('l', 3); // 인덱스 3부터 'l'의 첫 번째 등장 인덱스를 찾음
console.log(index2); // 출력: 3
String.lastIndexOf()란? 주어진 문자열에서 특정 부분 문자열의 마지막으로 등장하는 인덱스를 반환합니다. 해당 부분 문자열이 없으면 -1을 반환합니다.
const lastIndex = str.lastIndexOf(searchValue, fromIndex);
const str = 'Hello, World! Hello';
const index1 = str.lastIndexOf('o'); // 'o'의 마지막 등장 인덱스를 찾음
console.log(index1); // 출력: 18
const index2 = str.lastIndexOf('l', 10); // 인덱스 10부터 역순으로 'l'의 마지막 등장 인덱스를 찾음
console.log(index2); // 출력: 10