Bug: String.prototype.endsWith

# Axel Rauschmayer (14 years ago)

harmony:string_extras I’ve found a small bug:

String.prototype.endsWith = function(s) { var t = String(s); return this.lastIndexOf(t) === this.length - t.length; }; Interaction:

"".endsWith("/")

true

"#".endsWith("//")

true

"##".endsWith("///")

true

Fix (e.g.): String.prototype.endsWith = function(s) { var t = String(s); var index = this.lastIndexOf(t) return index >= 0 && index === this.length - t.length; };

# Xavier MONTILLET (14 years ago)

[Nope, wasn't deliberate]

I tested and both are as fast apparently but doing it the "hard" way seems slow. But maybe that's because I didn't do it properly.

And a function isAt could be useful. But it needs another name :-*

jsperf.com/endswith

# Rick Waldron (14 years ago)

That jsperf is too noisy to actually be measuring the performance of anything. If you want to test the performance of just the logic in question

  • then that should be all that exists.

See: jsperf.com/endwithlogic

From a web dev perspective... fallback definitions should always try to

minimize the number of other function calls they make.

# Rick Waldron (14 years ago)

Note, next to the "Filter" option, above the chart, click "All"

# David Herman (14 years ago)

Fixed, thanks.

Dave, digging his way out of a massive backlog...