jquery - How to insert new line after N char count in javascript? -
i have string may have new line '\n' char in it. want insert new line '\n' after every 4 (or n) chars in string.
for example:
1) input: "i john doe."
output: "i am\njohn\ndoe"
in above example inserting '\n' after 4 char including space
2) input: "i\nam john doe"
output: "i\nam j\nohn \ndoe"
in above example inserting space after 4 chars after first '\n' present in string
3) input: 12345\n67890
output: 1234\n5\n6789\n0
4) input: "1234\n56\n78901"
output: "1234\n56\n7890\n1"
so far have created function inserts '\n' after every 4 chars but not consider '\n' if present in original string.
function addnewlines(str) { if (str.length >= 4) { var result = ''; while (str.length > 0) { result += str.substring(0, 4) + '\n'; str = str.substring(4); } return result; } return str; }
i call function on every keypress , pass original string , output , use further. hope understand meant here. should preserve inserted new lines.
let me know can explain further. more examples.
here best guess being asked :
function addnewlines (str) { return str.replace (/(?!$|\n)([^\n]{4}(?!\n))/g, '$1\n'); }
some test strings , results :
"i john doe.", -> "i am\n joh\nn do\ne." "i\nam john doe", -> "i\nam j\nohn \ndoe" "12345\n67890", -> "1234\n5\n6789\n0" "1234\n56\n78901", -> "1234\n56\n7890\n1" "abcd\nefgh\nijkl", -> "abcd\nefgh\nijkl\n" "1234", -> "1234\n" "12341234" -> "1234\n1234\n"
for of whom regular expressions mysterious here breakdown:
---------------------------- (?! check following character(s) not | ------------------------- $|\n beginning of string or newline character | | --------------------- ) | | | -------------------- ( start of capture group 1 | | || ------------------ [^\n] single character other newline | | || | -------------- {4} previous element repeated 4 times | | || | | ----------- (?! check following character(s) not | | || | | | --------- \n newline | | || | | | | ------- ) | | || | | | | |------ ) end of capture group 1 | | || | | | | || ---- /g in replace causes matches processed | | || | | | | || | /(?!$|\n)([^\n]{4}(?!\n))/g
Comments
Post a Comment