LoginSignup
1
0

More than 1 year has passed since last update.

JavaScript 文字列操作メソッド 用途別チートシート

Last updated at Posted at 2022-07-23

判定系

文字列が指定された文字列で始まるかどうかを真偽値で返す

/**
 * startsWith(searchString, <position>)
 * @param {searchString: string} - 呼び出された文字列の先頭を検索する文字列。
 * @param {position: number} - 呼び出された文字列内で検索を開始する位置(指定しない場合は0)。
 * @return {result: boolean} - 呼び出された文字列が指定された文字列で始まるかどうか。
 */
const str = 'Saturday night plans';

console.log(str.startsWith('Sat')); // => true

console.log(str.startsWith('Sat', 3)); // => false

文字列が指定された文字列で終わるかどうかを真偽値で返す

/**
 * endsWith(searchString, <position>)
 * @param {searchString: string} - 呼び出された文字列の末尾を検索する文字列。
 * @param {position: number} - 呼び出された文字列内で検索を開始する位置(指定しない場合はstr.length)。
 * @return {result: boolean} - 呼び出された文字列が指定された文字列で終わるかどうか。
 */
const str1 = 'Cats are the best!';

console.log(str1.endsWith('best!')); // => true

console.log(str1.endsWith('best', 17)); // => true

const str2 = 'Is this a question?';

console.log(str2.endsWith('question')); // => false

文字列が指定した文字列を含むかどうかを真偽値で返す

/**
 * includes(searchString, <position>)
 * @param {searchString: string} - 呼び出された文字列内を検索する文字列。
 * @param {position: number} - 呼び出された文字列内内の検索を開始する位置(指定しない場合は0)。
 * @return {result: boolean} - 指定された文字列が呼び出された文字列内のどこかにあるかどうか。
 */
const sentence = 'The quick brown fox jumps over the lazy dog.';

const smallFox = 'fox';
const bigFox = 'Fox';

console.log(sentence.includes(smallFox)); // => true
console.log(sentence.includes(bigFox)); // => false

検索系

指定されたインデックスの箇所にある文字を返す

/**
 * charAt(index)
 * @param {index: number} - 負の整数を指定した場合は、文字列の末尾からカウントバックする。
 * @return {result: string | undefined} - 指定された位置にある単一の文字。
 *                                      - インデックスが見つからない場合は、空文字。
 */
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.charAt(4)); // => q

指定した部分文字列が最初に出現するインデックスを返す

/**
 * indexOf(searchString, <position>)
 * @param {searchString: string} - str内を検索する文字列。
 * @param {position: number} - str内の検索を開始する位置(指定しない場合0)。
 * @return {result: number} - 指定された文字列がstr内のどこかにある場合、最初に出現するインデックス。見つからない場合-1。
 */
const paragraph =
  'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(indexOfFirst); // => 40
console.log(paragraph.indexOf(searchTerm, indexOfFirst + 1)); // => 52

指定した部分文字列が最後に出現するインデックスを返す

/**
 * lastIndexOf(searchString, <position>)
 * @param {searchString: string} - str内を検索する文字列。
 * @param {position: number} - str内の検索を開始する位置(末尾ではなく先頭からカウント、指定しない場合infinity)。
 * @return {result: number} - 指定された文字列がstr内のどこかにある場合、最後に出現するインデックス。見つからない場合-1。
 */
const paragraph =
  'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';

console.log(paragraph.lastIndexOf(searchTerm)); // => 52

呼び出された文字列のうち、指定した部分文字列にマッチしたものを返す

/**
 * match(regexp)
 * @param {regexp: string} - 正規表現オブジェクト。
 * @return {result: object | string[]} - 一致するものがあった場合、最初に一致した文字列とそれに関する情報。
 *                                     - 正規表現にグローバルフラグが指定されている場合、一致した文字列の配列。
 */
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex1 = /[A-Z]/;
const regex2 = /[A-Z]/g;
console.log(paragraph.match(regex1));
// => [
//   'T',
//   index: 0,
//   input: 'The quick brown fox jumps over the lazy dog. It barked.',
//   groups: undefined
// ]
console.log(paragraph.match(regex2)); // => ["T", "I"]

呼び出された文字列の正規表現に最初に一致したインデックスを返す

/**
 * search(regexp)
 * @param {regexp: string} - 正規表現オブジェクト。
 * @return {result: number} - regexpに一致した文字列が最初に出現したインデックス。
 */
const paragraph =
  'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex)); // => 43

console.log(paragraph[paragraph.search(regex)]); // => "."

加工系

文字列を引数に取り、元の文字列に連結した新しい文字列を返す

/**
 * concat(concatString)
 * @param {concatString} - 元の文字列に連結する文字列。複数指定可能。
 * @return {string} - 提供された文字列の結合されたテキストを含む新しい文字列。
 */
const str1 = 'Hello';
const str2 = 'World';

console.log(str1.concat(' ', str2)); // => Hello World
console.log(str2.concat(', ', str1)); // => World, Hello

呼び出された文字列を指定された数コピーした新しい文字列を返す

/**
 * repeat(count)
 * @param {count: number} - 呼び出された文字列をコピーする回数。
 * @return {result: string} - 指定された数コピーを繰り返した新しい文字列。
 */
const chorus = "Because I'm happy. ";

console.log(chorus.repeat(3)); // => Because I'm happy. Because I'm happy. Because I'm happy

呼び出された文字列の一部をパターンに一致した一部を置換した新しい文字列を返す

/**
 * replace(regexp, newSubstr)
 * replace(substr, newSubstr)
 * @param {regexp: string} - 正規表現オブジェクト。グローバルフラグを付加すれば先頭以外の出現箇所も置換できる。
 * @param {substr: string} - newSubstrに置換される文字列。
 * @param {newSubstr: string} - regexpに一致した or substrで指定された部分文字列を置換する文字列。
 * @return {result: string} - regexpに一致した or substrで指定された部分文字列がnewSubstrに置換された新しい文字列。
 */
const p =
  'The quick brown fox jumps over the lazy dog. If the dog 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?"

const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// => "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

呼び出された文字列の一部をパターンに一致した全部を置換した新しい文字列を返す

/**
 * replaceAll(regexp, newSubstr)
 * replaceAll(substr, newSubstr)
 * @param {regexp: string} - 正規表現オブジェクト。グローバルフラグを付加すれば先頭以外の出現箇所も置換できる。
 * @param {substr: string} - newSubstrに置換される文字列。
 * @param {newSubstr: string} - regexpに一致した or substrで指定された部分文字列を置換する文字列。
 * @return {result: string} - regexpに一致した or substrで指定された部分文字列がnewSubstrに置換された新しい文字列。
 */
const p =
  'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

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

const regex = /Dog/gi;
console.log(p.replaceAll(regex, 'ferret'));
// => "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

呼び出された文字列の一部を切り出した新しい文字列を返す

/**
 * slice(indexStart, <indexEnd>)
 * @param {indexStart: number} - 返される部分文字列に含める最初の文字のインデックス。
 * @param {indexEnd: number} - 返される部分文字列から除外する最初の文字のインデックス。
 * @return {result: string} - 呼び出された文字列から指定されたインデックスの箇所を切り取った新しい文字列。
 */
const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31)); // => "the lazy dog."

console.log(str.slice(4, 19)); // => "quick brown fox"

console.log(str.slice(-4)); // => "dog."

console.log(str.slice(-9, -5)); // => "lazy"

呼び出された文字列を指定された文字列ごとに分割し、分割した文字列を配列に格納して返す

/**
 * split(separator, <limit>)
 * @param {separator: string} - 分割が発生する箇所を説明するパターン。
 * @param {limit: number} - 配列に含まれる部分文字列の数を制限する正の整数。
 * @return {result: string[]} - 分割された部分文字列の配列。
 */
const str = 'The quick brown fox jumps over the lazy dog.';

const words1 = str.split(' ');
console.log(words1); // => ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']

const words2 = str.split(' ', 3);
console.log(words2); // => ['The', 'quick', 'brown']

大文字 ⇄ 小文字

呼び出された文字列を全て小文字に置換した新しい文字列を返す

/**
 * toLowerCase()
 * @return {result: string} - 全て小文字に置換された新しい文字列。
 */
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toLowerCase()); // => "the quick brown fox jumps over the lazy dog."

呼び出された文字列を全て大文字に置換した新しい文字列を返す

/**
 * toUpperCase()
 * @return {result: string} - 全て大文字に置換された新しい文字列。
 */
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toUpperCase()); // => "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

パディング

結果の文字列が指定された長さに達するように、現在の文字列を指定された文字列で先頭にパディングして返す

/**
 * padStart(targetLength, <padString>)
 * @param {targetLength: number} - パディング後の長さ。
 * @param {padString: string} - パディングに使用する文字列。targetLengthに収まらない場合、切り捨てられる。
 * @return {result: string} - パディングされた文字列。省略した場合、" "。
 */
const str1 = '5';

console.log(str1.padStart(2, '0')); // => "05"

const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');

console.log(maskedNumber); // => => "************5581"

結果の文字列が指定された長さに達するように、現在の文字列を指定された文字列で末尾にパディングして返す

/**
 * padEnd(targetLength, <padString>)
 * @param {targetLength: number} - パディング後の長さ。
 * @param {padString: string} - パディングに使用する文字列。targetLengthに収まらない場合、切り捨てられる。
 * @return {result: string} - パディングされた文字列。省略した場合、" "。
 */
const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.')); // => "Breaded Mushrooms........"

const str2 = '200';

console.log(str2.padEnd(5)); // => "200  "

空白のトリミング

呼び出された文字列の先頭から空白を取り除いた新しい文字列を返す

/**
 * trimStart()
 * @return {result: string} - 呼び出された文字列の先頭から空白を取り除いた新しい文字列。
 */
const greeting = '   Hello world!   ';

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

console.log(greeting.trimStart()); // => "Hello world!   ";

呼び出された文字列の末尾から空白を取り除いた新しい文字列を返す

/**
 * trimEnd()
 * @return {result: string} - 呼び出された文字列の末尾から空白を取り除いた新しい文字列。
 */
const greeting = '   Hello world!   ';

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

console.log(greeting.trimEnd()); // => "   Hello world!";

参考

1
0
2

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