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
function addSpaces(input) {
  // Split input into an array
  let arr = input.split('');

  // Iterate over the array
  for(let i = 2; i < arr.length; i += 3) {
    // If there's no space after 2 characters, add one
    if(arr[i] !== ' ') {
      arr.splice(i, 0, ' ');
      i++; // Increment i to account for added space
    }

    // If there's no space after 3 characters, add one
    if((i + 1) < arr.length && arr[i + 1] !== ' ') {
      arr.splice(i + 1, 0, ' ');
    }
  }

  // Join array back into a string and return
  return arr.join('');
}

// Example usage
let input = '12hello345world';
let output = addSpaces(input);
console.log(output); // "12 hello 345 world"
677 chars
27 lines

gistlibby LogSnag