Home > Net >  Insert a character in a string based on character placement in another string
Insert a character in a string based on character placement in another string

Time:04-07

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!

CodePudding user response:

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)

CodePudding user response:

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))
, ""))

  • Related