0

Im trying to Add a few methods to the Javascript String Object. one of the main methods im trying to add is a substring count function

String.prototype.substring_count = function(delimiter){
    return {THIS IS WHAT I NEED THE STRING FOR}.split(delimiter).length;
}

Where do you access the string in the String object?

1 Answer 1

2

Use this. In the documentation, it is mentioned

If the method is on an object's prototype chain, this refers to the object the method was called on

in this case, the string itself

String.prototype.substring_count = function(delimiter){
    return this.split(delimiter).length;
}

console.log('test,123'.substring_count(','));

Sign up to request clarification or add additional context in comments.

2 Comments

I thought it was that, I have used prototyping before but i thought it had a certain variable within the String Object thanks anyway.
@JohnHudson, yes, this in a prototype method will refer to the object, in this case,the string itself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.