Skip to content

Commit

Permalink
Optional position argument
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Victor Homyakov committed Jan 26, 2013
1 parent fa1f899 commit e06ad15
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions src/prototype/lang/string.js
Expand Up @@ -770,33 +770,47 @@ Object.extend(String.prototype, (function() {
}

/**
* String#startsWith(substring) -> Boolean
* String#startsWith(substring[, position]) -> Boolean
* - substring (String): The characters to be searched for at the start of this string.
* - [position] (Number): The position in this string at which to begin searching for `substring`; defaults to 0.
*
* Checks if the string starts with `substring`.
*
* ##### Example
*
* 'Prototype JavaScript'.startsWith('Pro');
* //-> true
* 'Prototype JavaScript'.startsWith('Java', 10);
* //-> true
**/
function startsWith(pattern) {
function startsWith(pattern, position) {
position = Object.isNumber(position) ? position : 0;
// We use `lastIndexOf` instead of `indexOf` to avoid tying execution
// time to string length when string doesn't start with pattern.
return this.lastIndexOf(pattern, 0) === 0;
return this.lastIndexOf(pattern, position) === position;
}

/**
* String#endsWith(substring) -> Boolean
* String#endsWith(substring[, position]) -> Boolean
* - substring (String): The characters to be searched for at the end of this string.
* - [position] (Number): Search within this string as if this string were only this long;
* defaults to this string's actual length, clamped within the range established by this string's length.
*
* Checks if the string ends with `substring`.
*
* ##### Example
*
* 'slaughter'.endsWith('laughter')
* // -> true
* 'slaughter'.endsWith('laugh', 6)
* // -> true
**/
function endsWith(pattern) {
var d = this.length - pattern.length;
function endsWith(pattern, position) {
pattern = String(pattern);
position = Object.isNumber(position) ? position : this.length;
if (position < 0) position = 0;
if (position > this.length) position = this.length;
var d = position - pattern.length;
// We use `indexOf` instead of `lastIndexOf` to avoid tying execution
// time to string length when string doesn't end with pattern.
return d >= 0 && this.indexOf(pattern, d) === d;
Expand Down

0 comments on commit e06ad15

Please sign in to comment.