LoginSignup
0
0

More than 1 year has passed since last update.

【Javascript】Strings(2)学習ノート

Last updated at Posted at 2021-06-05

初めに

Stringについて学習した内容のoutput用記事です。

※内容に間違いなどがある場合はご指摘をよろしくお願いします。
※こちらの記事はあくまでも個人で学習した内容のoutputとしての記事になります。

前回の記事:
https://qiita.com/redrabbit1104/items/d68a8f79420a2a0320a6

文字列の大小

英語の文字列に大文字と小文字が混ざっている場合、文字列を小文字にするにはtoLowerCase()、大文字にするにはtoUpperCase()を使います。

const bank = "Mitsubishi UFJ Bank";

console.log(bank.toLowerCase());
//mitsubishi ufj bank

console.log(bank.toUpperCase());
//MITSUBISHI UFJ BANK

これを応用すれば名前が大小混ざっている文字列を最初の文字だけ大文字にし、残りの部分を小文字にすることができます。

const accountName = "toMaS";
const accountNameCorrect =
accountName[0].toUpperCase() + accountName.toLowerCase().slice(1);

console.log(accountNameCorrect);
//Tomas

trim()メソッドで要らない空白を削除

emailが正しいかどうかをチェックする場合に、trim()メソッドを使い空白を取り除くことができます。

const email = "test@yahoo.co.jp";
const inputEmail = "   Test@YahoO.co.Jp \n";

const lowerEmail = inputEmail.toLowerCase();
const trimmedEmail = lowerEmail.trim();
console.log(trimmedEmail);
//test@yahoo.co.jp

コンソールで確認するとemailと入力したinputEmailが一致しています。

console.log(email === trimmedEmail);
//true

文字列の変更

replace()メソッドを使えば、対象の文字列を変更することができます。

const pages = "The page you were looking for doesn't exist.";
console.log(pages.replace("doesn't exist", "exists"));
//The page you were looking for exists exist.

また、replaceAll()で対象の文字列を全て変更できます。

const replaceTest = "Home Home Home Home";
console.log(replaceTest.replaceAll("Home", "School"));
//School School School School

Boolean

文字列が存在するか調べるにはincludes()メソッド、対象の文字列で始まるかどうかを調べるにはstartsWith()メソッド、対象の文字列で終わるかを調べるにはendsWith()メソッドを使います。結果はtrueかfalseになります。

const pages = "The page you were looking for doesn't exist.";

console.log(pages.includes("you"));
//true

console.log(pages.startsWith("page"));
//false

console.log(pages.endsWith("exist."));
//true

参考サイト

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/trim
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/replace
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

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