Javascript Prototype String - accessing string value

蹲街弑〆低调 提交于 2021-02-17 05:17:33

问题


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:


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(','));


来源:https://stackoverflow.com/questions/33477092/javascript-prototype-string-accessing-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!