0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[JavaScript][Instance Methods] repeat, replaceメソッドとは (文字列→ 繰返し、文字列→置換)

Posted at

概要

repeat()String インスタンスのメソッドで、文字列を指定回数だけ繰り返した新しい文字列を返します。
replace()String インスタンスのメソッドで、文字列中の指定した部分を置換した新しい文字列を返します。

つまり、

  • repeat は「文字列 → 繰り返し文字列」
  • replace は「文字列 → 置換後の文字列」
    の操作を担うインスタンスメソッドです。

目次

基本構文

JavaScript
// repeat: 文字列を繰り返す(文字列の長さを利用)
const str = "#";
const word = "hello";
console.log(str.repeat(word.length)); 
// 出力結果 "#####"

// replace: 文字列を置換
const text = "Hello World";
console.log(text.replace("World", "JavaScript")); 
// 出力結果 "Hello JavaScript"

repeat と replace の比較

repeatメソッド

JavaScript
const maskChar = "#";
const target = "secret";
console.log(maskChar.repeat(target.length)); 
// 出力結果 "######"
  • 対象: 文字列
  • 戻り値: 指定回数繰り返した文字列
  • 用途: マスク文字列作成、装飾文字列生成など

replaceメソッド

JavaScript
const sentence = "I love JavaScript";
console.log(sentence.replace("JavaScript", "TypeScript"));
// 出力結果 "I love TypeScript"
  • 対象: 文字列
  • 戻り値: 置換後の文字列
  • 用途: 部分文字列の置換、文字列フォーマット修正など

比較結果

メソッド 対象 役割 戻り値
repeat 文字列 指定回数文字列を繰り返す 文字列
replace 文字列 指定部分を置換する 文字列

活用例

1. マスク処理(最後の4文字以外を#に置換)

JavaScript
function maskify(cc) {
  const last4 = cc.slice(-4);
  const masked = "#".repeat(cc.length - 4) + last4;
  return masked;
}

console.log(maskify("1234567890"));
// 出力: "######7890"

2. 単語置換

JavaScript
const str = "I like cats";
console.log(str.replace("cats", "dogs")); 
// 出力: "I like dogs"

3. 複数文字列置換(正規表現使用)

JavaScript
const text = "apple, banana, apple";
console.log(text.replace(/apple/g, "orange")); 
// 出力: "orange, banana, orange"

参考リンク

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?