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

196
Views
JavaScript: Insert a character after every N characters

I have a string, which always has a lenght of 32:

var str = "34v188d9cefa401f988563fb153xy04b";

Now I need to add a minus (-) after following number of characters:

  • First minus after 8th character
  • Second minus after 12th character
  • Third minus after 16th character
  • Fourth minus after 20th character

Output should be:

34v188d9-cefa-401f-9885-63fb153xy04b

So far I have tried different calculations with e.g.:

str.split('').reduce((a, b, c) => a + b + (c % 6 === 4 ? '-' : ''), '');

But I don't get the expected result.

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

0

You could use a regex replacement:

var str = "34v188d9cefa401f988563fb153xy04b";
var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
console.log(output);

about 4 years ago · Juan Pablo Isaza Report

0

If you want to use reduce you can do something like this

var str = "34v188d9cefa401f988563fb153xy04b";


const result = str.split('').reduce((res, c, i) => {
  const hiphensPositions = [7, 11, 15, 19]
  return res + c + (hiphensPositions.includes(i)?'-':'')
}, '')

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

     var str = "34v188d9cefa401f988563fb153xy04b";
     var a="" 
     for (let i in str){if (i == 7 || i==11 ||  i==15  ||  i == 
      19){a = a+str[i]+"-"} else{a+=str[i] }}

should do it.

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!