Count in String and Object
2015-10-23 07:25
435 查看
How
to count string occurrence in string?
var temp = "This is a string."; // the g in the regular expression says to search the whole string // rather than just find the first occurrence var count = (temp.match(/is/g) || []).length; alert(count);http://stackoverflow.com/a/4009768/2177408
/** Function count the occurrences of substring in a string; * @param {String} string Required. The string; * @param {String} subString Required. The string to search for; * @param {Boolean} allowOverlapping Optional. Default: false; * @author Vitim.us http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240 */ function occurrences(string, subString, allowOverlapping) { string += ""; subString += ""; if (subString.length <= 0) return (string.length + 1); var n = 0, pos = 0, step = allowOverlapping ? 1 : subString.length; while (true) { pos = string.indexOf(subString, pos); if (pos >= 0) { ++n; pos += step; } else break; } return n; }
Usage
occurrences("foofoofoo", "bar"); //0 occurrences("foofoofoo", "foo"); //3 occurrences("foofoofoo", "foofoo"); //1
allowOverlapping
occurrences("foofoofoo", "foofoo", true); //2
Matches:
foofoofoo 1 '----' 2 '----'http://stackoverflow.com/a/7924240/2177408
How
to efficiently count the number of keys/properties of an object in JavaScript?
What's the fastest way to count the number of keys/properties of an object? It it possible to do this without iterating over the object? i.e. without doingvar count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) count++;http://stackoverflow.com/q/126100/2177408
To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, FF 4+, or Safari 5+:
Object.keys(obj).length
Browser compatibility
Object.keys
documentation
(includes a method you can add to non-ECMA5 browsers)
http://stackoverflow.com/a/4889658/2177408
相关文章推荐
- 动态代理
- PO BO VO DTO POJO DAO概念及其作用(转)
- Objective-C RunTime那些事儿
- Objective-C中不同方式实现锁
- Xcode升级后插件失效的原理与修复办法
- IOS开发系列--Objective-C之协议、代码块、分类
- Objective 多态
- Objective-C基本语法
- OC内存管理高级
- JSONObject转换JSON--将Date转换为指定格式
- JSONObject、JSONArray
- spring mvc配置ObjectMapper忽略无法识别的字段,以及一些博客推荐
- gm: error while loading shared libraries: libpng15.so.15: cannot open shared object file: No such file or directory
- Swift and ObjectiveC Interop (Swift 与 Objective-C 之间的交互)
- Fatal error: Using $this when not in object context in 解决方法
- Objective-C学习-UILabel的使用
- Objective-C 程序设计 第六章
- 【Objective-C学习记录】01-基础概念
- Objective-C编码规范(待补充)
- Objective-C Runtime 运行时之二:成员变量与属性