JSFiddle - React, Tailwind, and code Playground
by Arun Tummala
JavaScript
function solution(string) {
var stringLength = string.length,
smallNumber = [];
string = removeSpacesAndDashes(string)
if(stringLength < 5) {
smallNumber = splitStringByIndex(string,2)
console.info(smallNumber.join('-'))
return smallNumber.join('-')
} else {
return formatString(string)
}
}
function removeSpacesAndDashes(string) {
return string.replace(/\s/g, '').replace(/-/g, '')
}
function formatString(string) {
var splitArray = [] ,
strLength = parseInt(string.length/3),
i=0,
threeArray = [];
console.info('strLength',strLength)
for(i; i<strLength; i++) {
if(splitArray.length === 0) {
splitArray = (splitStringByIndex(string, 3))
console.info('first splitArray',splitArray)
threeArray.push(splitArray[0]);
} else {
console.info('splitArray in else ',splitArray, 'i', i)
debugger
splitArray = (splitStringByIndex(splitArray[1], 3))
console.info('splitArray after assignment',splitArray, 'i', i)
threeArray.push(splitArray[0]);
console.info('threeArray in else', threeArray)
}
}
console.info('threeArray',threeArray.join('-') +'-'+extraTextAtEnd(string,strLength))
return threeArray.join('-') + '-' + extraTextAtEnd(string,strLength)
}
function splitStringByIndex(string,index) {
debugger
if(string.length > index) {
return [string.slice(0,index), string.slice(index)]
} else {
return [string]
}
}
function extraTextAtEnd(string,strLength) {
if(string.length%3 === 0) {
return ''
} else {
return string.substring(strLength*3);
}
}
solution('0022')