I want using regex to detect all the new line character (\n) that are put by users by mistake. For example
# abcd abcd abcd abcd
efgh efgh efgh efgh
## ijk ijk ijk ijk ijk ijk
lmn lmn lmn
# opq opq opq opq
rst rst rest rst
To be corrected to following
# abcd abcd abcd abcd efgh efgh efgh efgh
## ijk ijk ijk ijk ijk ijk lmn lmn lmn
#opq opq opq opq rst rst rest rst
I am trying to use this regex string :
\s*\n+[\s]*[^#]+
to be replaced by "" (blank string)
ie. Find a \n character that
\n should not have a # after it. Eg. \n # . Because # should always start a new line, and if # too is included and replaced by "" it will start appearing on the same line as previous one.The answer after replacement with \n is this, which is not desired:
# abcd abcd abcd abcdfgh efgh efgh efgh## ijk ijk ijk ijk ijk ijkmn lmn lmn# opq opq opq opqst rst rest rst
How can I improve my regex string and replacement string to get what I need as output?
You may use this regex:
(?:\s*\n)+\s*(?!\s*#)|^\s+|[ \t]*$
Code:
const s = `# abcd abcd abcd abcd
efgh efgh efgh efgh
## ijk ijk ijk ijk ijk ijk
lmn lmn lmn
# opq opq opq opq
rst rst rest rst
`;
var r = s.replace(/(?:\s*\n)+\s*(?!\s*#)|^\s+|[ \t]*$/mg, '');
console.log(r);
You may try with that:
^[ \t]*([#]+[^\n]+)\n[ \t]*([^#\n]+.*?)\n
and replace by this:
$1$2
const regex = /^[ \t]*([#]+[^\n]*?)[ \t]*\n[ \t]*([^#\n]+.*?)\n/gm;
const str = `# abcd abcd abcd abcd
efgh efgh efgh efgh
## ijk ijk ijk ijk ijk ijk
lmn lmn lmn
# opq opq opq opq
rst rst #rest rst
`;
const subst = `$1$2`;
const result = str.replace(regex, subst);
console.log(result);