javascript linkを使用して任意の文字列にリンクをつける

javascript linkを使用して任意の文字列にリンクをつける

javascriptで、linkを使用して任意の文字列にリンクをつけるサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

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

linkを使用

「link」を使用すると任意の文字列に指定したリンクを付けることが可能です。

<input id="btn" type="button" value="ボタン"/>

<script>

'use strict';

document.getElementById('btn').onclick = function(){ 

      const str = 'mebee';

      // リンクを作成
      document.write( str.link("https://mebee.info/") );

};

<script>

実行結果

また、以下のコードを、

document.getElementById('btn').onclick = function(){ 
      const str = 'mebee';
      // リンクを作成
      document.write( str.link("https://mebee.info/") );
};

document.getElementByIdの省略化やforEach、アロー関数化を使用して、簡潔に記述することもできます。

btn.onclick = () =>{	
    const str = 'mebee';
    document.write( str.link("https://mebee.info/") );
}