LoginSignup
0
0

More than 5 years have passed since last update.

js 与えられた文字の真中を返す

Last updated at Posted at 2018-05-10

与えられた文字の中間の文字を返してください。
単語の長さが偶数の場合は、中央の2文字を返してください。
*与えられる文字はアルファベットになります

function getMiddle(s){
  //write your code
}

getMiddle("test")//"es"
getMiddle("testing")//"t"
getMiddle("middle")//"dd"
getMiddle("A")//"A"

使ったもの

if
length
charAt();
slice();
Math.floor();

考えかた

与えられた文字を2で割る
割り切れるかどうかでif文を設定

コード

getMiddle = (s) => {
  var middle = s.length / 2;
  return (s.length % 2) 
    ? s.charAt(Math.floor(middle))
    : s.slice(middle - 1, middle + 1);
}

その他コード


getMiddle = (s) =>{
  return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}

他にもコード浮かんだ方、コメントお願いします。

0
0
5

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
0
0