Programing

substr과 substring의 차이점은 무엇입니까?

crosscheck 2020. 9. 29. 07:20
반응형

substr과 substring의 차이점은 무엇입니까?


차이점은 무엇입니까

alert("abc".substr(0,2));

alert("abc".substring(0,2));

둘 다 "ab"를 출력하는 것 같습니다.


차이점은 두 번째 주장에 있습니다. 두 번째 인수 substring는 중지 할 색인 (포함하지 않음)이지만 두 번째 인수 substr는 반환 할 최대 길이입니다.

연결?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring


substr( MDN )은 매개 변수를 (from, length).
substring( MDN )은 매개 변수를 (from, to).

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

substring또 다른 문자열 추출 방법 인 slice 와 마찬가지로 take 인덱스 를 기억할 수 있습니다 .

0부터 시작하는 경우 두 방법 중 하나를 사용할 수 있습니다.


yatima2975의 답변에서 암시했듯이 추가 차이점이 있습니다.

substr()문자열 끝에서 오프셋으로 음의 시작 위치를 허용합니다. substring()하지 않습니다.

에서 MDN :

start가 음수이면 substr ()은 문자열 끝에서 문자 인덱스로 사용합니다.

따라서 기능적 차이점을 요약하면 다음과 같습니다.

substring(begin-offset, end-offset-exclusive)시작 오프셋이 0이상인 경우

substr(begin-offset, length) 시작 오프셋도 음수 일 수 있습니다.


내가 최근에 발견 한 또 다른 문제점은 IE 8 "abcd".substr(-1)에서는를 잘못 반환 "abcd"하는 반면 Firefox 3.6은 "d"제대로 반환 한다는 것입니다. slice둘 다에서 올바르게 작동합니다.

이 주제에 대한 자세한 내용은 여기 에서 찾을 수 있습니다 .


주요 차이점은

substr ()을 사용하면 반환 할 최대 길이를 지정할 수 있습니다.

substring ()을 사용하면 인덱스를 지정할 수 있으며 두 번째 인수는 포함되지 않습니다.

substr ()과 substring () 사이에는 동일한 인수 및 음수 인수 처리와 같은 몇 가지 추가 미묘함이 있습니다. 또한 substring ()과 slice ()는 비슷하지만 항상 같은 것은 아닙니다.

  //*** length vs indices:
    "string".substring(2,4);  // "ri"   (start, end) indices / second value is NOT inclusive
    "string".substr(2,4);     // "ring" (start, length) length is the maximum length to return
    "string".slice(2,4);      // "ri"   (start, end) indices / second value is NOT inclusive

  //*** watch out for substring swap:
    "string".substring(3,2);  // "r"    (swaps the larger and the smaller number)
    "string".substr(3,2);     // "in"
    "string".slice(3,2);      // ""     (just returns "")

  //*** negative second argument:
    "string".substring(2,-4); // "st"   (converts negative numbers to 0, then swaps first and second position)
    "string".substr(2,-4);    // ""
    "string".slice(2,-4);     // ""

  //*** negative first argument:
    "string".substring(-3);   // "string"        
    "string".substr(-3);      // "ing"  (read from end of string)
    "string".slice(-3);       // "ing"        

차이점은 두 번째 매개 변수입니다. 두 번째 매개 변수는 두 숫자이지만 두 가지 다른 것을 예상합니다.

하위 문자열을 사용할 때 두 번째 매개 변수는 포함하지 않는 첫 번째 색인입니다.

var s = "string";
s.substring(1, 3); // would return 'tr'

var s = "another example";
s.substring(3, 7); // would return 'ther'

substr을 사용할 때 두 번째 매개 변수는 하위 문자열에 포함 할 문자 수입니다.

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

슬라이스 대 Substr 대 하위 문자열 대 [] 메서드

이러한 각 자바 스크립트 메소드에는 성능상의 이점이 있습니다. 그에 따라 이러한 기능을 사용하십시오.


substring () : "start"와 "end"매개 변수가 2 개 있습니다.

  • start parameter is required and specifies the position where to start the extraction.
  • end parameter is optional and specifies the position where the extraction should end.

If the end parameter is not specified, all the characters from the start position till the end of the string are extracted.

var str = "Substring Example";
var result = str.substring(0, 10);
alert(result);

Output : Substring

If the value of start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as start.

var str = "Substring Example";
var result = str.substring(10, 0);
alert(result);

Output : Substring

substr(): It has 2 parameters "start" and "count".

  • start parameter is required and specifies the position where to start the extraction.

  • count parameter is optional and specifies the number of characters to extract.

var str = "Substr Example";
var result = str.substr(0, 10);
alert(result);


Output : Substr Exa

If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If count is 0 or negative, an empty string is returned.

var str = "Substr Example";
var result = str.substr(11);
alert(result);

Output : ple


The big difference is, substr() is a deprecated method that can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. You should work to remove their use from your code. And the substring() method succeeded and specified the former one.


substring(startIndex, endIndex(not included))

substr(startIndex, how many characters)

const string = 'JavaScript';

console.log('substring(1,2)', string.substring(1,2)); // a
console.log('substr(1,2)', string.substr(1,2)); // av

참고URL : https://stackoverflow.com/questions/3745515/what-is-the-difference-between-substr-and-substring

반응형