I need to create a program in JS that receives a requirment of user digits (ex: 11223655871) and returns the sequence with '-' between even numbers and '#' between odd numbers, ie the result will be: 1 # 12-2365 # 587 # 1
I need to create a program in JS that receives a requirment of user digits (ex: 11223655871) and returns the sequence with '-' between even numbers and '#' between odd numbers, ie the result will be: 1 # 12-2365 # 587 # 1
var num=11223655871;
var result="";
var digits = num.toString().split('');
var realDigits = digits.map(Number);
for(i = 0; i < realDigits.length; i++)
{
var value1 = realDigits[i];
var value2 = realDigits[i+1];
result += value1;
if(value1 % 2 != 0 && value2 % 2 != 0) {
result += "#";
}else if(value1 % 2 == 0 && value2 % 2 == 0){
result += "-";
}
}
result = result.substring(0,(result.length - 1));
console.log(result);
Concepts:
You can use the Array.prototype.reduce function, observe the last character of the first argument and the second argument, see if they are the even / odd, and return the number with potentially the symbol in the middle.
I think regular expression is the best way to format your string.
let meuNum = 11223655871;
let numFormatdo = '${meuNum}'.replace(/([13579])([13579])/g, '$1#$2')
.replace(/([02468])([02468])/g, '$1-$2');
console.log(numFormatdo);