take input value. if after the first 2 charakters is no space, put space between. if ater the next 3 is no space, put space between in javascript
You can split the input string into an array, then iterate over the array checking for 2 and 3 character chunks that need whitespace added. Here's an example function that does that:
index.tsx
functionaddSpaces(input) {
// Split input into an arraylet arr = input.split('');
// Iterate over the arrayfor(let i = 2; i < arr.length; i += 3) {
// If there's no space after 2 characters, add oneif(arr[i] !== ' ') {
arr.splice(i, 0, ' ');
i++; // Increment i to account for added space }
// If there's no space after 3 characters, add oneif((i + 1) < arr.length && arr[i + 1] !== ' ') {
arr.splice(i + 1, 0, ' ');
}
}
// Join array back into a string and returnreturn arr.join('');
}
// Example usagelet input = '12hello345world';
let output = addSpaces(input);
console.log(output); // "12 hello 345 world"