Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between slice() and substr() in JavaScript?

Can I ask what the difference is between string object slice() and substr() in JavaScript?

like image 452
dramasea Avatar asked Dec 28 '10 13:12

dramasea


People also ask

What is the difference between substr and slice in JavaScript?

slice() extracts parts of a string and returns the extracted parts in a new string. substr() extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.

What is a slice in JavaScript?

JavaScript Array slice() The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.

How do you slice a substring in JavaScript?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.

What is substring in JavaScript with example?

Definition and UsageThe substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.


1 Answers

They have different signatures, .slice() is:

string.slice(beginIndex, endIndex)

Whereas .substr() is:

string.substr(beginIndex, length);

So for example, if we have "1234" and wanted "23", it would be:

"1234".slice(1,3)
//or...
"1234".substr(1,2)

They also have different behavior for the more-rarely used negative indexes, look at the MDC documentation for .slice() and .substr() for full descriptions.

like image 142
Nick Craver Avatar answered Oct 16 '22 08:10

Nick Craver