Create a new String method in JavaScript?

moon_man41 asked this question 4 months ago
moon_man41 on Jan 20

In JavaScript, how do I apply a method directly to a string?

So I can use something like this:


And have it work on any string?

2 suggested answers
timmy123 on Jan 21

This creates a upperCaseFirstLetter() method you can apply to strings:

String.prototype.upperCaseFirstLetter = function() {
  return this.charAt(0).toUpperCase() + this.slice(1)

And you can use it like this:

"bananas".upperCaseFirstLetter() // "Bananas"
0 replies
yaboy01 on Jan 21

You can create a custom string method like this:

String.prototype.yourMethodName = function() {
  return this // string is accessed via this
0 replies