LoginSignup
0
0

es6のテンプレートリテラルを使って、行頭のインデントを削除

Last updated at Posted at 2023-10-13

コードの見栄えとして、テンプレート文字列でも、行頭にインデントを入れたい

そんな時用。

注意点は、行頭のスペースとタブを単純に削除するだけなので、全部のインデントが消えます。

そのため、HTMLなどのテンプレートとして使いたい時は、インデントが消えてしまうので注意です。

その他、定型文などで整形する時も気をつけて使いましょう。


// テンプレート文字列の行頭のスペースまたはタブを削除
const escapeIndent = (strs, ...keys) => {
  let result = [];
  strs.forEach((_, i)=>{
    result.push(strs[i].replace(/^(  |\t)+/, '').replace(/\n(  |\t)+/g, '\n'));
    if(i < strs.length - 1) result.push(keys[i]);
  });
  return result.join('');
};

const x = '<XXX>';
const y = '<YYY>';

const text = escapeIndent`aaa
    bbb${x}
        ccc
    ${y}

    ddd`;

console.log(text);

/*
aaa
bbb<XXX>
ccc
<YYY>

ddd
*/
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