Home > Enterprise >  Insert space after specific amount of numbers within a string
Insert space after specific amount of numbers within a string

Time:10-20

I got an array with a lot of strings that are badly formatted. I need to add a space to the string after the first three numbers within the String with JavaScript. The main problem is that I don't have a specific index to insert the space because the number of characters before the first three numbers vary or dont exist at all.

Example Input:

[
   "A12345678",
   "ABC12345678",
   "1234 56 7 8",
   "12 345 67 8",
   "AB12345678BVC",
]

Desired Output:

[
   "A123 45678",
   "ABC123 45678",
   "123 45678",
   "123 45678",
   "AB123 45678BVC",
]

I thought it may be solvable with replaceAll spaces to get an unbroken string and then do a for loop over each character per string and then solve this by type checking the characters to add a space at the desired position, but I get a huge amount of these arrays from the backend and it may end up in a terrible performance this way.

The other idea I got is to solve this by using Regex like in this example from a tutorial, but unfortunately I suck at writing Regex. I'd be really grateful if somebody can help me with this.

CodePudding user response:

You could use String.replace() along with Array.map() to add the required space. First of all we remove all spaces from each string, then add the space at the required position.

const input = [
   "A12345678",
   "ABC12345678",
   "1234 56 7 8",
   "12 345 67 8",
   "AB12345678BVC",
]

const result = input.map(v => v.replace(/\s/g,'').replace(/(\d{3})/, '$1 '));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related