자바스크립트 문자열 substr()
예
텍스트에서 부분 문자열 추출:
let text = "Hello world!";
let result = text.substr(1, 4);"
위치 2에서 시작:
let result = text.substr(2);
아래에 더 많은 예가 있습니다.
정의 및 사용
이 substr()
메서드는 문자열의 일부를 추출합니다.
메서드 는 substr()
지정된 위치에서 시작하여 지정된 문자 수를 반환합니다.
이 substr()
메서드는 원래 문자열을 변경하지 않습니다.
문자열 끝에서 문자를 추출하려면 음수 시작 위치를 사용하십시오.
통사론
string.substr(start, length)
매개변수
Parameter | Description |
start | Required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string. |
length | Optional. The number of characters to extract. If omitted, it extracts the rest of the string |
반환 값
유형 | 설명 |
문자열 | 추출된 부분이 포함된 문자열입니다. 길이
가 0이거나 음수이면 빈 문자열이 반환됩니다 . |
더 많은 예
첫 번째만:
let result = text.substr(0, 1);
마지막만:
let result = text.substr(text.length-1, 1);
마지막 6:
let result = text.substr(-5, 5);
브라우저 지원
substr()
ECMAScript1(ES1) 기능입니다.
ES1(JavaScript 1997)은 모든 브라우저에서 완벽하게 지원됩니다.
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |