Home > Software design >  A function that takes a string, divides it into parts of 2 characters each, and then returns an arra
A function that takes a string, divides it into parts of 2 characters each, and then returns an arra

Time:09-03

I need to implement a splitString function that takes a string str, divides it into parts of 2 characters each, and then returns an array of those parts.

If the string contains an odd number of characters, I need to add a '_' after the last character.

For example:

splitString('123456'); *// ['12', '34', '56']*

splitString('ab cd ef'); *// ['ab', ' c', 'd ', 'ef']*

splitString('abc'); *// ['ab', 'c_']*

splitString(' '); *// [' _']*

splitString(''); *// []*`
function splitString(str) {

    const result = [];

    for (let i = 0; i < str.length; i  = 2) {
      if (str % 2 === 0) {
        result.push(str.substring(i, i   2));
      }
      if (str % 2 !== 0) {
        
      }
  }
  return result;
}

CodePudding user response:

There's a few ways to do this. First, with your approach, I'd suggest only doing the padding once, not one every iteration.

Also str % 2 probably isn't what you want, but rather str.length % 2

function splitString(str) {

    const result = [];
    // force it to be even-length, padding if necessary
    if (str.length % 2 !== 0) {
      str = str   "_";
    }

    
    for (let i = 0; i < str.length; i  = 2) {
      result.push(str.substring(i, i 2));
    }
    return result;
}

console.log(splitString("abc"));
console.log(splitString("abcd"));
console.log(splitString(""));

Another option is to use a regular expression

function splitString(str) {
  if (str.length % 2 !== 0) str  = "_";
  // str.split will return an array like
  // ["", "ab", "", "cd"]
  // so we use `.filter` to remove the empty elements
  return str.split(/(..)/g).filter(s => s)
}

console.log(splitString("abc"));
console.log(splitString("abcd"));

CodePudding user response:

I would do it with a different approach - using the rest and spread operators with a while loop.

Also, I suggest that the 0 length string be short circuited, as its result is always the same ([] - an empty array).

const strings = [
  '123456',
  'ab cd ef',
  'abc',
  ' ',
  '',
]

const splitString = (str) => {
  if (!str.length) return []
  let arr = [...str] // creating a local variable
  let ret = [] // creating the return variable

  while (arr.length) {
    // destructuring the two characters
    const [first, second = "_", ...rest] = arr
    // adding the new items to the return array
    ret = [...ret, ""   first   second]
    // modifying the local variable, so on the next "while"
    // run it's updated
    arr = rest
  }

  return ret
}

const c = strings.map(splitString)
console.log(c)

  • Related