archives

« Bugzilla Issues Index

#498 — String.endsWith and String.startsWith will have unexpected behavior when used with a regular expression


Regular expressions can be used in place of strings for many string methods. But consider startsWith/endsWith:

"foo".startsWith(/f/) // => false
"/a/b/c".startsWith(/a/) // => true

A developer who is confused about these methods won't get any real feedback. No type error, and though it will not match as they intended it will largely appear to work.

One option would be:

String.prototype.startsWith = function (pattern) {
if (typeof pattern == "object" && pattern.constructor == RegExp) {
return this.search(pattern == 0)
}
return this.indexOf(pattern) == 0;
};

but endsWith is harder:

String.prototype.endsWith = function (pattern) {
if (typeof pattern == "object" && pattern.constructor == RegExp) {
var newReg = new RegExp(pattern.source + '$');
return newReg.test(this);
}
...
}

Not sure if mucking about with the regex is kosher.

String.prototype.contains has the same issue I suppose.


> var newReg = new RegExp(pattern.source + '$');

Nit: This wouldn't work if pattern is a disjunction, like /a|b/.

I'm not sure, but maybe
new RegExp('(?:' + pattern.source + ')$')
would be correct.

I think supporting regexps here is an excellent idea.


Agree that supporting regular expressions would be nice. But, as already highlighted, endsWith might be a concern. Mainly I'm commenting to point out that Jason's modification of Ian's code still wouldn't work, since it doesn't account for RegExp flags. You can't simply add the flags and make it work, either, because /m changes the meaning of the $ anchor.


fixed in rev20 editor's draft

Defined endWidth and startsWith as throwing if first argument is a RegExp. This allows for a adding RegExp support in a future editions.


fixed in rev20 draft, Oct. 28, 2013


Seems `String.prototype.contains` was forgotten about during the fix. See bug 2407.