30秒学会 JavaScript 片段 · 2018年8月27日

30秒学会 JavaScript 片段 – indentString

Indents each line in the provided string.

Use String.replace and a regular expression to add the character specified by indent count times at the start of each line.
Omit the third parameter, indent, to use a default indentation character of ' '.

代码片段

const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));

使用样例

indentString('Lorem\nIpsum', 2); // '  Lorem\n  Ipsum'
indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'