Remove extra CrLf's from textarea

M

McKirahan

I'd like to use regular expressions to remove extraneous Carriage Return
Line Feeds (CrLf) from a textarea before the form is submitted.

I'd like to remove all trailing CrLf's and convert all instances of 3
consectutive CrLf's to just 2.

I first escape() the textarea and match "%0D%0A" (i.e. CrLf).

Here's what I've been testing; watch for word-wrap:

<html>
<head>
<title>fix_crlf.htm</title>
<script type="text/javascript">
function fix() {
var form = document.forms[0];
var body = escape(form.Body.value);
// try to remove all trailing CrLf's
body = body.replace(/\%0D\%0A$/g,"");
// try to convert all 3 CrLf's to 2
body = body.replace(/\%0D\%0A\%0D\%0A\%0D\%0A/g,"\%0D\%0A\%0D\%0A");
body = unescape(body);
// update the form field to see if it worked -- NOT!
form.Body.value = body;
}
</script>
</head>
<body>
<form>
<textarea name="Body" rows="30"></textarea>
<input type="button" value="fix()" onclick="fix()">
</form>
</body>
</html>


I thought the "g" would handle multiple instances (of both cases) or do I
have to do a "for" loop?

Can anyone advise me? Thanks in advance.

Note: JavaScript will be enabled as this is for a browser-based application
that requires it.
 
M

McKirahan

Andrew Urquhart said:
<snip />

strData = strData.replace(/(\r\n\s*){2,}/g, "\r\n\r\n");

The above finds 2 or more CrLfs with optional whitespace between them
and replaces it all with 2 CrLfs. If you're not bothered about the
chance of whitespace then:

strData = strData.replace(/(\r\n){3,}/g, "\r\n\r\n");


Thank you very much for your reply.

But how would I remove all trailing (and leading) CrLf's?

Thanks again.
 
M

McKirahan

McKirahan said:
Thank you very much for your reply.

But how would I remove all trailing (and leading) CrLf's?

Thanks again.


Perhaps it would be?

strData = strData.replace(/^(\r\n\s*)/g, "");
strData = strData.replace(/(\r\n\s*)$/g, "");
 
M

McKirahan

Andrew Urquhart said:
McKirahan said:
Perhaps it would be?

strData = strData.replace(/^(\r\n\s*)/g, "");
strData = strData.replace(/(\r\n\s*)$/g, "");

strData = strData.replace(/^[\r\n]+|[\r\n]+$/g, "");
--
Andrew Urquhart
- FAQ: http://jibbering.com/faq
- Archive: http://groups.google.com/groups?group=comp.lang.javascript
- Reply: www.andrewu.co.uk/about/contact/


Thanks, Andrew.

I recently bought a copy of O'Reilly's "Mastering Regular Expressions" which
I'm wading through; someday I'll be self-sufficient (maybe).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top