您的位置:首页 > 移动开发 > Objective-C

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 doing
var 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: