LoginSignup
4
2

More than 5 years have passed since last update.

js 回文の真偽判定

Last updated at Posted at 2016-12-12

文章が回文かどうか真偽判定する

script.js
function palindrome(str) {
 //write your code.
}
palindrome("My age is 0, 0 si ega ym.")//true

出力結果 例

script.js
palindrome("eye") //true
palindrome("_eye") // true
palindrome("My age is 0, 0 si ega ym.")//true
palindrome("0_0 (: /-\ :) 0-0")//true
palindrome("1 eye for of 1 eye.") //false

試したコード

script.js
function palindrome(str) {
 var i =str.replace(/[\W_]/g, '').toLowerCase();
 return i === i.split('').reverse().join('');
}

考え方

.replace(/[\W_]/g, '')で英数字以外の記号を取り除く
.toLowerCase()で小文字に変換して変数iに格納する。
split('').reverse().join('')で分割、逆順、結合をして変数iと比較する。

もっと簡潔に美しくかけるよ!という方、コメントお待ちしております。

参考リンク

String.prototype.replace()
String.prototype.toLowerCase()

4
2
0

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
4
2