Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
Insert space after specific amount of numbers within a string

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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; }

about 4 years ago · Juan Pablo Isaza Report

0

Use

const texts = [
  "A12345678",
  "ABC12345678",
  "1234 56 7 8",
  "12 345 67 8",
  "AB12345678BVC"
]
for (const text of texts) {
    console.log(text, '->', text.replace(/\s+/g,'').replace(/\d{3}(?!$)/, '$& '));
}

I.e.

  • Remove whitespaces first, then
  • Add space after first 3 digits if these digits are not at the end of the string.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!