1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

javascriptで文字列の間に記号を入れたい

Last updated at Posted at 2021-08-12
function addSignToString(number){
  const numArray = String(number).match(/.{2}/g);
  const reducer = (accumulator, currentValue) => accumulator +  ' > ' + currentValue;
  signIncludedString = numArray.reduce(reducer);
  return signIncludedString;
}

console.log(addSignToString(121212));
// 12 > 12 > 12

修正案_1

@e92gr sann
@hxiqz sann
コメントありがとうございます。

function addSignToString(number){
  const stringNum = String(number);

  if (isNullOrUndefined(number)) {
      return '';
  } else if (stringNum.length < 2 ) {
      return number;
  } else if (stringNum.length % 2 === 1) {
      const last = stringNum.substring(stringNum.length - 1, stringNum.length);
      return addSign(stringNum) + ' > ' + last;
  } else {
     return addSign(stringNum);
  }
}

function addSign(number) {
  if(!['string', 'number', 'bigint'].includes(typeof number)) return '';
  const numArray = String(number).match(/.{2}/g);
  return numArray !== null ? numArray.join(' > ') : '';
}

function isNullOrUndefined(number) {
    if (number === null | number === undefined | number === '' | !number) {
        console.log('入力がありません');
        return true;
    }
}
console.log(addSignToString(121212));
// 12 > 12 > 12
console.log(addSignToString(122));
// 12 > 2
console.log(addSignToString());
// 入力がありません
1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?