Skip to content

Commit e06ad15

Browse files
author
Victor Homyakov
committed
Optional position argument
Added optional position argument to `String#startsWith`, `String#endsWith`, as described in https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/startsWith and https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/endsWith. Documented new arguments and examples.
1 parent fa1f899 commit e06ad15

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/prototype/lang/string.js

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -770,33 +770,47 @@ Object.extend(String.prototype, (function() {
770770
}
771771

772772
/**
773-
* String#startsWith(substring) -> Boolean
773+
* String#startsWith(substring[, position]) -> Boolean
774+
* - substring (String): The characters to be searched for at the start of this string.
775+
* - [position] (Number): The position in this string at which to begin searching for `substring`; defaults to 0.
774776
*
775777
* Checks if the string starts with `substring`.
776778
*
777779
* ##### Example
778780
*
779781
* 'Prototype JavaScript'.startsWith('Pro');
780782
* //-> true
783+
* 'Prototype JavaScript'.startsWith('Java', 10);
784+
* //-> true
781785
**/
782-
function startsWith(pattern) {
786+
function startsWith(pattern, position) {
787+
position = Object.isNumber(position) ? position : 0;
783788
// We use `lastIndexOf` instead of `indexOf` to avoid tying execution
784789
// time to string length when string doesn't start with pattern.
785-
return this.lastIndexOf(pattern, 0) === 0;
790+
return this.lastIndexOf(pattern, position) === position;
786791
}
787792

788793
/**
789-
* String#endsWith(substring) -> Boolean
794+
* String#endsWith(substring[, position]) -> Boolean
795+
* - substring (String): The characters to be searched for at the end of this string.
796+
* - [position] (Number): Search within this string as if this string were only this long;
797+
* defaults to this string's actual length, clamped within the range established by this string's length.
790798
*
791799
* Checks if the string ends with `substring`.
792800
*
793801
* ##### Example
794802
*
795803
* 'slaughter'.endsWith('laughter')
796804
* // -> true
805+
* 'slaughter'.endsWith('laugh', 6)
806+
* // -> true
797807
**/
798-
function endsWith(pattern) {
799-
var d = this.length - pattern.length;
808+
function endsWith(pattern, position) {
809+
pattern = String(pattern);
810+
position = Object.isNumber(position) ? position : this.length;
811+
if (position < 0) position = 0;
812+
if (position > this.length) position = this.length;
813+
var d = position - pattern.length;
800814
// We use `indexOf` instead of `lastIndexOf` to avoid tying execution
801815
// time to string length when string doesn't end with pattern.
802816
return d >= 0 && this.indexOf(pattern, d) === d;

0 commit comments

Comments
 (0)