I have a string which may have new line '\n' char in it. Now I want to insert new line '\n' after every 4 (or N) chars in that string.
For example:
1) INPUT: "I am 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' already present in the string
3) INPUT: 12345\n67890
OUTPUT: 1234\n5\n6789\n0
4) INPUT: "1234\n56\n78901"
OUTPUT: "1234\n56\n7890\n1"
So far I have created a function which inserts '\n' after every 4 chars but it does not consider '\n' if it is already present in the 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 this function on every keypress and pass the original string and get output and use it further. I hope you understand what I meant to say here. It should preserve the previously inserted new lines.
Let me know I can explain further. With more examples.
I have a string which may have new line '\n' char in it. Now I want to insert new line '\n' after every 4 (or N) chars in that string.
For example:
1) INPUT: "I am 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' already present in the string
3) INPUT: 12345\n67890
OUTPUT: 1234\n5\n6789\n0
4) INPUT: "1234\n56\n78901"
OUTPUT: "1234\n56\n7890\n1"
So far I have created a function which inserts '\n' after every 4 chars but it does not consider '\n' if it is already present in the 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 this function on every keypress and pass the original string and get output and use it further. I hope you understand what I meant to say here. It should preserve the previously inserted new lines.
Let me know I can explain further. With more examples.
Share Improve this question edited May 19, 2013 at 10:18 ʞɹᴉʞ ǝʌɐp asked May 19, 2013 at 7:42 ʞɹᴉʞ ǝʌɐpʞɹᴉʞ ǝʌɐp 5,6508 gold badges41 silver badges65 bronze badges 17-
Please confirm your second example, The first inserted \n is after 5 characters, why? More examples would help also. I also find the * around the
\n
characters confusing, make the input and output exactly the strings you need. – HBP Commented May 19, 2013 at 7:59 - I have removed the *. Please do not consider the quotes it is just to represent string. – ʞɹᴉʞ ǝʌɐp Commented May 19, 2013 at 8:22
- Your description says you want to add a newline after every four characters (or four characters after an existing newline), but your examples show only a single newline added to the string. Which is it, only one newline added in total, or a newline after every four characters? – Michael Geary Commented May 19, 2013 at 8:25
-
Thanks, but your second example output is still confusing, should there not be a
\n
beforeDoe
? You also state "inserting space after 4 characters" : under what conditions? – HBP Commented May 19, 2013 at 8:25 -
1
Shouldn't your first example have one more
\n
too? And what should this string be turned into: 'ABCD\nEFGH\nIJKL' - should it simply preserve the existing newlines, or add additional newlines? The reason we're all guessing is that you haven't written a plete specification. You need to explain what you want in every edge case and provide a prehensive list of inputs and outputs. – Michael Geary Commented May 19, 2013 at 8:33
5 Answers
Reset to default 5Here is my best guess as to what is being asked for :
function addNewLines (str) {
return str.replace (/(?!$|\n)([^\n]{4}(?!\n))/g, '$1\n');
}
Some test strings and their results :
"I am 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 those of you for whom regular expressions are mysterious here is a breakdown:
---------------------------- (?! Check that following character(s) are not
| ------------------------- $|\n Beginning of string or a newline character
| | --------------------- )
| | | -------------------- ( Start of capture group 1
| | || ------------------ [^\n] Any single character other than newline
| | || | -------------- {4} Previous element repeated exactly 4 times
| | || | | ----------- (?! Check that following character(s) are not
| | || | | | --------- \n a newline
| | || | | | | ------- )
| | || | | | | |------ ) End of capture group 1
| | || | | | | || ---- /g in replace causes all matches to be processed
| | || | | | | || |
/(?!$|\n)([^\n]{4}(?!\n))/g
function parseInput(str, char, length){
var split = str.split(char),
regex = RegExp('(.{' + length + '})','g');
split[split.length-1] = split[split.length - 1].replace(regex, '$1' + char);
return split.join(char);
}
console.log(parseInput("I am John Doe.", "\n", 4));
// output = "I am\n Joh\nn Do\ne."
- Split the string by "\n" str.split("\n"). You get an array of strings.
- Do your additional parsing and manipulation checking the element length and putting the result in a new array results.
- Join the strings using results.join("\n").
This will remove "\n" duplicates too if you avoid to append or prepend "\n" to results elements.
Here is my code:
function ngram_insert (n, ins, input)
{
var output = "";
var i = 0;
while (i < strlen(input))
{
if (i > 0 && i % n == 0)
{
output += ins;
}
output += input[i];
i++;
}
return output;
}
Test:
var output = ngram_insert (3, "\n", "This is a test.");
function f(n, ins, str) {
if (str.length == 0)
return "";
var i = str.indexOf("\n"), len = str.length, newStr;
if (i == -1) {
i = 1;
newStr = str[0];
}
else {
newStr = str.substring(0, i + 1);
}
var k = 1;
while (k + i < len) {
newStr += str[k + i];
if (k % n == 0) {
newStr += ins;
}
k++;
}
return newStr;
}
Calling f(4, "\n", "I\nam John Doe");
returns "I\nam J\nohn \nDoe"