Skip to content
Browse files

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.
  • Loading branch information...
1 parent fa1f899 commit e06ad15a3bab8267ce5413a7ba93cfcada34bf0e @victor-homyakov committed Jan 27, 2013
Showing with 20 additions and 6 deletions.
  1. +20 −6 src/prototype/lang/string.js
View
26 src/prototype/lang/string.js
@@ -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;

0 comments on commit e06ad15

Please sign in to comment.
Something went wrong with that request. Please try again.