Reputation: 3893
I have a string consist of 7 digits, I need a function that returns "true" if the string created by repetition of just 2 digits, something like :
check('9669669'); // true
check('0000001'); // true
check('5555555'); // false
check('1111123'); // false
I want to know the easiest way. thanks.
Upvotes: 0
Views: 151
Reputation: 104780
You can replace the first character globally, twice.
function check2(str){
var fun= function(s){
return s.replace(RegExp(s.charAt(0), 'g'), '')
};
str= fun(str);
return !!(str && fun(str)=== '');
}
var A= ['9669669', '0000001', '5555555', '1111123'];
A.map(check2);
/* returned value: (Array) [true,true,false,false] */
Upvotes: 2
Reputation: 318202
Something like this should work, pushing unique characters in an array, and checking if it's length is 2
function check(str) {
var arr = [], i = 0, parts = str.split('');
for (var j=0; j<parts.length; j++) {
if (arr.indexOf(parts[j]) === -1) arr.push(parts[j]);
}
return arr.length === 2;
}
or more fancy
function check(str) {
return str.split('').reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c); return p;
}, []).length === 2;
}
Upvotes: 2