diff --git a/snippets/indentString.md b/snippets/indentString.md new file mode 100644 index 000000000..0fe2502f2 --- /dev/null +++ b/snippets/indentString.md @@ -0,0 +1,16 @@ +### 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 `' '`. + +```js +const indentString = (str, count, indent = ' ') => + str.replace(/^/mg, indent.repeat(count)); +``` + +```js +indentString('Lorem\nIpsum', 2); // ' Lorem\n Ipsum' +indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum' +``` diff --git a/tag_database b/tag_database index f9148976d..55c9927df 100644 --- a/tag_database +++ b/tag_database @@ -113,6 +113,7 @@ httpGet:utility,url,browser,intermediate httpPost:utility,url,browser,intermediate httpsRedirect:browser,url,intermediate hz:function,intermediate +indentString:string,utility,beginner indexOfAll:array,intermediate initial:array,beginner initialize2DArray:array,intermediate diff --git a/test/indentString/indentString.js b/test/indentString/indentString.js new file mode 100644 index 000000000..5bf39d559 --- /dev/null +++ b/test/indentString/indentString.js @@ -0,0 +1,3 @@ +const indentString = (str, count, indent = ' ') => + str.replace(/^/mg, indent.repeat(count)); +module.exports = indentString; diff --git a/test/indentString/indentString.test.js b/test/indentString/indentString.test.js new file mode 100644 index 000000000..474523fb8 --- /dev/null +++ b/test/indentString/indentString.test.js @@ -0,0 +1,12 @@ +const expect = require('expect'); +const indentString = require('./indentString.js'); + +test('indentString is a Function', () => { + expect(indentString).toBeInstanceOf(Function); +}); +test('indentString is a Function', () => { + expect(indentString('Lorem\nIpsum', 2)).toBe(' Lorem\n Ipsum'); +}); +test('indentString is a Function', () => { + expect(indentString('Lorem\nIpsum', 2, '_')).toBe('__Lorem\n__Ipsum'); +});