根据字符在另一个字符串中的位置在字符串中插入一个字符

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

我有两个字符串:

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

const format = 'X-XX-X';

我需要创建一个新字符串,其中根据 format 中分隔符的位置在 originalSegments 中的字符集之间插入破折号。

括号中的每组一个字符等于一个format个字符,

[*] === X

期望的最终结果是:

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

我可以得到每个部分的长度 format:

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

originalSegments中的段数:

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

但我不确定下一步该做什么。

Array.prototype.reduce() 可以吗?非常感谢任何建议!

我会为你的案例提出这个解决方案

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)

这是另一种方法:

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

有趣的问题。另一个版本使用 regex 组匹配和 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)