const count1 = [
num => (('' + num).match(/1/g) || []).length,
num => num.toString().replace(/[^1]/g, '').length,
num => `${num}`.split('').filter(d => !~-d).length,
num => [...String(num)].reduce((s, d) => s + (d == 1), 0),
num => ''.split.call(num, 1).length - 1,
];
const numbers = [
23489,
-11,
-93481,
7211231,
0,
123.321,
Infinity,
NaN,
];
count1.map(f => numbers.filter(n => f(n) === 2)).forEach(n => console.log(n));
indexOf()
в лоб. Костыль только для двух повторов, но, по идее, быстрее регулярок:function haz2ones(str) {
const s = str.toString();
const search = '1';
let i = s.indexOf(search);
if (!~i) return false;
i = s.indexOf(search, i + 1);
if (!i) return false;
if (!!~s.indexOf(search, i + 1)) return false;
return true;
}
const tests = [
[1, false],
[11, true],
[111, false],
['1', false],
['11', true],
['111', false],
['100001', true],
['000011', true],
[12345678901234567890, true],
];
return tests.map(e => haz2ones(e[0]) === e[1] ? '+' : '- ' + e[0]);
// +,+,+,+,+,+,+,+,+