Indent string
Indents each line in the provided string.
- Use
String.prototype.replace()and a regular expression to add the character specified byindentcounttimes at the start of each line. - Omit the third argument,
indent, to use a default indentation character of' '.
const indentString = (str, count, indent = ' ') =>
str.replace(/^/gm, indent.repeat(count));正規表示式 (opens in a new tab)後面的全域標記
g指定將該表示式應用到輸入字串中能夠尋找到的儘可能多的匹配。 多行標記m指定分行符號的兩邊可能出現潛在的匹配。
indentString('Lorem\nIpsum', 2); // ' Lorem\n Ipsum'
indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'