两位一反,字符串两两更换位置

34 阅读1分钟
  • 转数组
/**
  两位一反,字符串两两更换位置,有19/20位iccid,统一按18位比较
  示例: 8986112221503188066
        986811221205138860 新
 */
export function iccidReveser(str) {
  const data = str.split('')
  const arr = []
  let i = 0

  while (i < data.length) {
    i && i++
    const last = data[i + 1]
    arr.push(last ? [data[i], last] : [data[i]])
    i++
  }
  const result = arr.map(k => k.reverse()).flat().join('').substring(0, 18)
  return result
}

  • 操作字符串
/**
 * 每两位翻转 iccid,向下取整,若length为奇数,返回少一位
 */
const reverseIccid = (iccid) => {
  if (iccid.startsWith('89')) {
    return iccid
  } else {
    let stringBuffer = ''
    for (let i = 0; i < Math.floor(iccid.length / 2); i++) {
      stringBuffer += iccid[i * 2 + 1]
      stringBuffer += iccid[i * 2]
    }
    return stringBuffer
  }
}