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

227
Views
Insert a character in a string based on character placement in another string

I have two strings:

const originalSegments = '[ABC][XYZ][123][789]';

const format = 'X-XX-X';

I need to create a new string where the dashes are inserted between sets of characters in originalSegments based on the placement of separators in format.

Each set of a characters between brackets is equal to one format character,

i.e. [*] === X

The desired end result is:

'[ABC]-[XYZ][123]-[789]'

I can get the length of each section in format:

const formatSections = format.split('-');
const formatSectionLengths = formatSections.map(section => section.length);
// => [1, 2, 1]

And the number of segments in originalSegments:

const originalSegmentsCount = (regexToString.match(/\]\[/g) || []).length + 1;
// => 4

But I'm not sure what to do next.

Would Array.prototype.reduce() work for this? Any advice is greatly appreciated!

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

0

Here is another approach:

const text='[ABC][XYZ][123][789]',
  pat='X-XX-X';

let txt=text.replaceAll("][","],[").split(",");
console.log(pat.split("").reduce((a,c)=>
 a + (c==="X"?txt.pop():c)
, ""))

about 4 years ago · Juan Pablo Isaza Report

0

I'd propose this solution for your case

const originalSegments = "[ABC][XYZ][123][789]";
//convert all segments to ["ABC","XYZ","123","789"]
const segments = originalSegments.split('[').filter(x => x).map(x => x.split(']')[0]);
const format = 'X-XX-X'
let result = []
let segmentIndex = 0
//loop through format to find X for the replacement
for(let i = 0; i < format.length; i++) {
  const character = format[i]
  //if the current character is X, replace with segment data
  if(character === "X") {
     result.push(`[${segments[segmentIndex]}]`)
     //check the next segment
     segmentIndex++
     continue
  }
  result.push(character)
}

//convert all results to a string
const finalResult = result.join("")

console.log(finalResult)

about 4 years ago · Juan Pablo Isaza Report

0

Interesting question. Another version using regex group matches and map

const originalSegments = '[ABC][XYZ][123][789]';
const format = 'X-XX-X';

const segs = originalSegments.match(/(\[[\w]+\])/g);
const output = [...format]
  .map((ch) => (ch === "X" ? segs.shift() : ch))
  .join("");
  
console.log(output)

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!