Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - Split Strings into pairs of characters


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of creating an array, you can directly access characters of the string with bracket notation.

const splitPairs = (input) => {
  if(!input) return [];
  let pairs = [];
  if(input.length % 2 !== 0) {input += '_'}
  for(let i = 0; i < input.length; i+= 2) {
    pairs.push(`${input[i] + input[i+1]}`)
  }
  return pairs;
}

let result1 = splitPairs('abc');//--> [ 'ab', 'c_' ]
console.log(result1);

let result2 = splitPairs('abcdef');//--> [ 'ab', 'cd', 'ef' ]
console.log(result2);

let result3 = splitPairs('retrograde');//--> [ 're', 'tr', 'og', 'ra', 'de' ]
console.log(result3);

let result4 = splitPairs('endurance');//--> [ 'en', 'du', 'ra', 'nc', 'e_' ]
console.log(result4);

let result5 = splitPairs('');//--> []
console.log(result5);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...