javascript 文字列の先頭から指定した文字列が含まれているかを判定する

javascript 文字列の先頭から指定した文字列が含まれているかを判定する

javascriptで、startsWithを使用して、文字列の先頭から指定した文字列が含まれているかを判定するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

startsWith使い方

startsWithを使用すると、文字列の先頭から、指定した文字列が含まれているかを判定することが可能です。

const str = "hello";

console.log( str.startsWith('he') ); // true
console.log( str.startsWith('hel') ); // true
console.log( str.startsWith('el') ); // false

第2引数に、開始位置を指定することも可能です。

const str = "hello";

console.log( str.startsWith('el',1) ); // true
console.log( str.startsWith('llo',2) ); // true
console.log( str.startsWith('el',2) ); // false

逆に、終了位置から判定する場合は「endsWith」を使用します。

const str = "hello";

console.log( str.endsWith('o') ); // true
console.log( str.endsWith('lo') ); // true
console.log( str.endsWith('ll') ); // false

console.log( str.endsWith('e',2) ); // true
console.log( str.endsWith('ll',4) ); // true
console.log( str.endsWith('ell',3) ); // false

サンプルコード

以下は、
「実行」ボタンをクリックすると、ランダムな「a~e」までの5個の文字列を生成して、
ランダムに生成した「a~e」までの文字が1文字に含まれているかを判定する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数で記述してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>

<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  const hoge = () => {

    // ランダムな「a~e」までの5文字の文字列を生成
    const str = "abcde";
    let randstr = '';

    const n = 5; // 繰り返し回数

    for (let i = 0; i < n; i++) {
      randstr += str[~~(Math.random() * str.length)];
    }

    // ランダムに生成した文字列を表示
    rand.innerHTML = randstr;

    // ランダムに生成した文字を表示
    const randchar = str[~~(Math.random() * str.length)]
    txt.innerHTML = randchar;

    // 結果を表示
    result.innerHTML = randstr.startsWith(randchar)

  }

  //フロントに表示する関数
  const disp = (arr, id) => {
    let text = [];
    // for ofを使用
    for (let item of arr) {
      text.push('<li class="list-group-item">' + item + '</li>');
    }
    //innerHTMLを使用して表示    
    document.getElementById(id).innerHTML = text.join('');
  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main container">


    <h2><span id="rand" class="badge bg-success">ランダムな文字列</span></h2>

    <h2><span id="txt" class="badge bg-success">ランダム文字</span></h2>

    <h2><span id="result" class="badge bg-success">結果</span></h2>


    <div class="row">
      <button id="btn" type="button" class="btn btn-warning">
        実行
      </button>
    </div>

  </div>

</body>

</html>

判定されていることが確認できます。