Reputation: 24061
I'm using the following regular expression to replace html tags with the same html tag plus a line break:
content = content.replace(new RegExp('(</.*?>)', 'gi'), '$1 \n').replace(/\/>/g,'/> \n');
Here's what happens in my site:
I write some text. I copy the text. I paste into a div and the above is run which adds line breaks. I then copy this text out of the div. I then add more content, and repeat the process.
The problem is that a further line break is added to previous content when I perform a copy and paste again. So the second time I do the above, I get two line breaks, third time, three line breaks etc.
How can I make the above expression replace tags with tags and line breaks and ignore (or replace again) tags that already have line breaks.
Upvotes: 2
Views: 289
Reputation: 13222
You can try this:
var content = "<Test>Test</Test><Test2>Test2</Test2><Test3 /><Test4>Test4</Test4>";
var regexTest = new RegExp('(</.*?>)(?!\\n.*)', 'gi');
var regexTest2 = new RegExp('/>(?!\\n.*)', 'g');
content = content.replace(regexTest, '$1\n').replace(regexTest2,'/>\n');
alert(content);
content = content.replace(regexTest, '$1\n').replace(regexTest2,'/>\n');
alert(content);
//remove linebreaks
content = content.replace(/\n/g, '');
alert(content);
This adds a negative lookahead (?!...)
so it checks to make sure there isn't already a \n
. If you get rid of the space between $1
and \n
and />
and \n
then you don't need the \\s
in the regex...
Upvotes: 1