Nice programing

String.slice와 String.substring의 차이점은 무엇입니까?

nicepro 2020. 9. 29. 18:40
반응형

String.slice와 String.substring의 차이점은 무엇입니까?


이 두 가지 방법의 차이점을 아는 사람이 있습니까?

String.prototype.slice
String.prototype.substring

slice()같은 작품 substring()몇 가지 다른 행동을.

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);

공통점 :

  1. 경우 start등호 stop: 빈 문자열을 반환
  2. stop생략 된 경우 : 문자열 끝까지 문자를 추출합니다.
  3. 인수 중 하나가 문자열의 길이보다 크면 문자열의 길이가 대신 사용됩니다.

구별 :substring()

  1. 경우 start > stop, 다음 substring사람들이 개 인자를 교환합니다.
  2. 인수 중 하나가 음수이거나 인 NaN경우 마치 그랬던 것처럼 처리됩니다 0.

구별 :slice()

  1. 경우 start > stop, slice()빈 문자열을 반환합니다. ( "")
  2. start음수 인 경우 : substr()Firefox 와 똑같이 문자열 끝에서 문자를 설정합니다 . 이 동작은 Firefox와 IE 모두에서 관찰됩니다.
  3. stop음수 인 경우 : 중지를 string.length – Math.abs(stop)(원래 값)으로 설정합니다. Math.max(0, string.length + stop), ECMA 사양 에서 다루는대로 0 (따라서 )으로 제한됩니다 .

출처 : 프로그래밍 및 개발의 기초 기술 : 자바 스크립트 : substr () vs substring ()


참고 : 급한 경우 및 / 또는 단답형을 찾고있는 경우 답변의 맨 아래로 스크롤하여 마지막 두 줄을 읽습니다.


사실을 말하면서 시작하겠습니다.

구문 :
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
참고 # 1 :slice()==substring()

그것은 무엇을합니까?
slice()메서드는 문자열의 일부를 추출하고 추출 된 부분을 새 문자열로 반환합니다.
substr()메서드는 지정된 위치의 문자에서 시작하여 문자열의 일부를 추출하고 지정된 수의 문자를 반환합니다.
substring()메서드는 문자열의 일부를 추출하고 추출 된 부분을 새 문자열로 반환합니다.
노트 2:slice()==substring()

원래 문자열을 변경합니까?
slice()안함
substr()안함
substring()안함
# 3 :slice()==substring()

음수를 인수로 사용 :
slice()문자열
substr()끝에서 시작하는 문자 선택 문자열 끝부터 시작하는 문자 선택
substring()Does n't Perform
Note # 3 :slice()==substr()

if the First Argument is Greater than the Second:
slice() Doesn't Perform
substr() since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring() will swap the two arguments, and perform as usual

the First Argument:
slice() Required, indicates: Starting Index
substr() Required, indicates: Starting Index
substring() Required, indicates: Starting Index
Note #4:slice()==substr()==substring()

the Second Argument:
slice() Optional, The position (up to, but not including) where to end the extraction
substr() Optional, The number of characters to extract
substring() Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()

What if the Second Argument is Omitted?
slice() selects all characters from the start-position to the end of the string
substr() selects all characters from the start-position to the end of the string
substring() selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()

so, you can say that there's a difference between slice() and substr(), while substring() is basically a copy of slice().

in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr().


Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn´t.

Here is his article about this http://www.bennadel.com/blog/2159-using-slice-substring-and-substr-in-javascript.htm


The one answer is fine but requires a little reading into. Especially with the new terminology "stop".

My Go -- organized by differences to make it useful in addition to the first answer by Daniel above:

1) negative indexes. Substring requires positive indexes and will set a negative index to 0. Slice's negative index means the position from the end of the string.

"1234".substring(-2, -1) == "1234".substring(0,0) == ""
"1234".slice(-2, -1) == "1234".slice(2, 3) == "3"

2) Swapping of indexes. Substring will reorder the indexes to make the first index less than or equal to the second index.

"1234".substring(3,2) == "1234".substring(2,3) == "3"
"1234".slice(3,2) == ""

--------------------------

General comment -- I find it weird that the second index is the position after the last character of the slice or substring. I would expect "1234".slice(2,2) to return "3". This makes Andy's confusion above justified -- I would expect "1234".slice(2, -1) to return "34". Yes, this means I'm new to Javascript. This means also this behavior:

"1234".slice(-2, -2) == "", "1234".slice(-2, -1) == "3", "1234".slice(-2, -0) == "" <-- you have to use length or omit the argument to get the 4.
"1234".slice(3, -2) == "", "1234".slice(3, -1) == "", "1234".slice(3, -0) == "" <-- same issue, but seems weirder.

My 2c.


The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:

substring (start, end)

Negative arguments are interpreted as zero. Too large values ​​are truncated to the length of the string:   alert ( "testme" .substring (-2)); // "testme", -2 becomes 0

Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:

alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"

slice

Negative values ​​are measured from the end of the line:

alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.

It is much more convenient than the strange logic substring.

A negative value of the first parameter to substr supported in all browsers except IE8-.

If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.


The only difference between slice and substring method is of arguments

Both take two arguments e.g. start/from and end/to.

You cannot pass a negative value as first argument for substring method but for slice method to traverse it from end.

Slice method argument details:

REF: http://www.thesstech.com/javascript/string_slice_method

Arguments

start_index Index from where slice should begin. If value is provided in negative it means start from last. e.g. -1 for last character. end_index Index after end of slice. If not provided slice will be taken from start_index to end of string. In case of negative value index will be measured from end of string.

Substring method argument details:

REF: http://www.thesstech.com/javascript/string_substring_method

Arguments

from It should be a non negative integer to specify index from where sub-string should start. to An optional non negative integer to provide index before which sub-string should be finished.


substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.

slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.

sample code for 'slice' in string

var str="Javascript";
console.log(str.slice(-5,-1));

output: crip

sample code for 'substring' in string

var str="Javascript";
console.log(str.substring(1,5));

output: avas

[*Note: negative indexing starts at the end of the string.]


For slice(start, stop), if stop is negative, stop will be set to:

string.length – Math.abs(stop)

rather than:

string.length – 1 – Math.abs(stop)

참고URL : https://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring

반응형