缩进字符串
缩进提供的字符串中的每一行。
- 使用
String.prototype.replace()和正则表达式,在每一行的开头添加由indent参数指定的字符count次。 - 如果省略第三个参数
indent,将使用默认的缩进字符' '。
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'