JavaScriptの5文字列メソッド.


文字列はテキスト形式で表現できるデータを保持するのに便利です.

1 . include ()
includes()メソッドは、1文字列が別の文字列内で見つかったかどうかを返すtrue or false .
const sentence = "The quick brown fox jumps over the lazy dog.";

const word = "fox";

console.log(
  `The word "${word}" ${
    sentence.includes(word) ? "is" : "is not"
  } in the sentence.`
); // The word "fox" is in the sentence.

2 . replace ()
replace ()メソッドは、pattern に置き換えられるreplacement . The pattern 文字列あるいはRegExp , とreplacement 文字列または各マッチに対して呼び出される関数です.If pattern が文字列の場合、最初の値だけが置き換えられます.
const p =
  "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
const regex = /dog/gi;

console.log(p.replace(regex, "ferret")); // The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?

console.log(p.replace("dog", "monkey")); // The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?

3 . split ()
split ()メソッドは、String 部分文字列の順序付きリストに、これらの部分文字列を配列に配置し、配列を返します.
const str = "The quick brown fox jumps over the lazy dog.";

const words = str.split(" ");
console.log(words[3]); // fox

const chars = str.split("");
console.log(chars[8]); // k

4 . startswith()
startswith()メソッドは、指定した文字列の文字で始まる文字列を返すかどうかを判断しますtrue or false 適宜.
const str = "Saturday night plans";

console.log(str.startsWith("Sat")); // true

5 . trim ()
trim ()メソッドは、文字列の両端から空白を削除します.このコンテキストの空白は、空白文字(スペース、タブ、ブレークスペースなど)、およびすべての行終端文字(LF、CRなど)です.
const greeting = " Hello world! ";

console.log(greeting); // " Hello world! "
console.log(greeting.trim()); // "Hello world!"