Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2014 (Bloomington, MN) with:

Ask Ben: Javascript Replace And Multiple Lines / Line Breaks

By Ben Nadel on

When I get the text out of a textarea in Javascript, how can I replace out the line breaks?

You are not the only one who has difficulty with line breaks in Javascript. I get a lot of questions about it, so hopefully this will help everyone out. If you come from a ColdFusion background, as I do, I think a lot of confusion comes from the fact that line breaks in ColdFusion are represented by the character 13 (new line character) followed by the character 10 (carriage return character)(ex. "#Chr( 13 )##Chr( 10 )#"). After dealing with this for so long, people instinctively try to replace out the same substring in Javascript text: "\n\r".

The problem is that in Javascript, line breaks are represented by the single new line character "\n", not the combination of new line and carriage return. To prove this, let's create a string in Javascript that uses the new line character "\n" to form multiple line:

  • var strMultiLineText =
  • "Karen didn't know how to feel any more. She had never liked girls\n" +
  • "\"that way,\" but she couldn't ignore the emotion, that surge of \n" +
  • "adrenaline that coursed through her body at the sight of Kimmie's\n" +
  • "wet, naked, voluptuous figure in the locker room showers.";

... Let's also create a textarea that has this same string, minus the "\n" characters:

  • <textarea id="text" style="width: 100% ; height: 100px ;"
  • >Karen didn't know how to feel any more. She had never liked girls
  • "that way," but she couldn't ignore the emotion, that surge of
  • adrenaline that coursed through her body at the sight of Kimmie's
  • wet, naked, voluptuous figure in the locker room showers.</textarea>

Ok, now let's alert both values (after the page has loaded) to see that they have the same format:

  • // Alert the Javascript text.
  • alert( strMultiLineText );
  •  
  • // Alert the textarea text.
  • alert( document.getElementById( "text" ).value );

After doing so, you can see that they have the same exact format. This is because when you pull text into Javascript, it treats line breaks as the single "\n" value. If you are not convinced, let's try to alert the index of the carriage return character:

  • // Alert the index of the first "\r" instance.
  • alert(
  • document.getElementById( "text" ).value.indexOf( "\r" )
  • );

This alerts to -1 which means that "\r" is NOT to be found in the string.

So, now that we know that new lines are represented by the single "\n" character, how can we go about stripping them out of the string? The same way we would go about stripping any character out of the string: using the Javascript String.Replace() method on a single character. Now, we could use a simple string replace method call, but that would only replace the first instance of the new line character. Since we want to strip out all new line characters, we are going to have to do a global replace using a regular expression:

  • // Strip out all line breaks.
  • var strSingleLineText = strMultiLineText.replace(
  • // Replace out the new line character.
  • new RegExp( "\\n", "g" ),
  •  
  • // Put in ... so we can see a visual representation of where
  • // the new line characters were replaced out.
  • " ... "
  • );
  •  
  • // Alert the new single-line text value.
  • alert( strSingleLineText );

When you alert this value, you will see that the text is all in one line (the alert box may add it's own line breaks for best viewing) with " ... " in place of the original new line values. It's that easy.

Now, you may notice something interesting: in the original text variable, I created new lines as "\n", however, when I replaced them out, I use the value "\\n". If you play around with the text, you might discover that passing both "\n" AND "\\n" will both work. While they both work, they work for two different reasons. "\n" passes the new line character. "\\n" passes the regular expression representation of the new line character. Since the "\" is a special character in Javascript use to escape the succeeding character, "\n" actually evaluates to "new line". "\\n" evalutes to "\n" in the regular expression, which Javascript treats as new line representation when executing the regular expression. This point is not so important, but comes into play when you learn more about regular expressions.

So, key points to take away:

  1. In Javascript, new lines are represented by a single "\n" character.
  2. Textarea values might have the character combos "\n\r" in the text box, but once they are pulled into Javascript, "\n\r" becomes JUST "\n".
  3. When replacing out new line characters, treat them as you would any other character. They are not special, they just have special notation.



Reader Comments

Hi Ben, I just recently found your blog and have been pouring through your posts with delight. One small thing with this post, i'm sure the sequence should be "\r\n" rather than "\n\r".

Reply to this Comment

Topper,

Thanks for the tip. I can never remember which it is. Whats nice about using something like regular expressions in a replace is that the order might not be important. For instance, i could do a replace with the expression [\r\n]{2} and it would replace any match of two of those characters, regardless of order. But of course that is only for RegExp. Thanks for pointing that out though.

Reply to this Comment

In order to remember whether or not it's \r\n or \n\r just use his simple memory trick...

boldrboldeturboldnbold ... as in line return.

It's a simple mnemonic trick that I made up a long time ago. Works like a charm. Great article btw.

Reply to this Comment

In order to remember whether or not it's \r\n or \n\r just use his simple memory trick...

return ... as in line return.

It's a simple mnemonic trick that I made up a long time ago. Works like a charm.

Reply to this Comment

none of this works for me! I can't get replace to find a single line break with \n or \r or any combination of either...

The replace just keeps failing to find my search string with multiple lines in it?

Reply to this Comment

Conrad,

Send me a text file that has the text you are using. Maybe there is something strange going on??? (ben [ at ] bennadel [ dot ] com).

Reply to this Comment

Thx alot.. !!

Having a vb origin I automatically presumed Replace meant replace ANY occurrence.. duh.. :)

Reply to this Comment

Thanks for the post it was most helpful however when I did some testing I found that in IE6 the textarea returns both \r and \n so when I wrote it to the database I was getting two line break characters.

The following fixed the problem for me:

val = val.replace(/\n/g,"<br/>").replace(/\r/g,"");

This now works in both IE6 and FireFox.

Regards

Ben

Reply to this Comment

@Ben,

Thanks for bringing that to our attention. I am getting frustrated with the difference in line breaks between browsers. It has recently cropped up in other endeavors and I am finding it irritating.

Reply to this Comment

How could you embed \n into your multi line javascript string without generating javascript error???

Reply to this Comment

@Bohush,

Can you give me an example of what you mean? Usually, when I want to add a new line to script, I just use "\n". For example,

alert( "Line 1\nLine 2\nLine 3" );

Reply to this Comment

Hi Ben,
sorry for such a hasty question, but whenever I want to use \n in javascript string it causes error. Example: alert("Line1\nLine2); will generate error because when submitted to browser it already looks like:
alert("Line1
Line2);
I think it is because I generate html files, including javascript in them, by php, but I am not still sure if I can use it directly in .html file.
Meanwhile I solved my problem by using double back slash ex: alert("Line1\\nLine2"); May be this is the way to do it in php. Thanks for your time, however if you know other solution(s) I would gladly to see it.
Bohush

Reply to this Comment

@Bohush,

I see what you are saying. I didn't realize that the page was going through other pre-page-processing. In that case, you might have to escape some of the special characters as you have done. It's like in ColdFusion pages, having to escape the hash sign (##) to use a single hash in the HTML.

Reply to this Comment

You can also strip tabs from your text:

var tab= RegExp( "\\t", "g" )
document.getElementById( "text" ).value= document.getElementById( "text" ).value.replace(tab, "")

Reply to this Comment

Thank you been for posting the following fix for IE - you posted it on my birthday no less! It is a great belated gift today!

"Thanks for the post it was most helpful however when I did some testing I found that in IE6 the textarea returns both \r and \n so when I wrote it to the database I was getting two line break characters.

The following fixed the problem for me:

val = val.replace(/\n/g,"<br/>").replace(/\r/g,"");

This now works in both IE6 and FireFox.

Regards

Ben

Posted by Ben on Nov 28, 2007 at 10:40 AM
"

Reply to this Comment

Ben,

This isn't my birthday, but I too would like to thank you for your post and follow-on comments... In my Javascripting experience, I've never had to do anything specifically for the '\r' character, so that didn't even cross my mind when I was trying to figure out why my replacement of '\n' with '<br>' hadn't cleared up my line-break problem. Thanks for saving me from having to delay my lunch to figure out a fix :)

On another note, I took a Data Structures class back in 1986 at the University of Michigan from a professor named Nadel. Any relation?

Sheldon Robertson
Ricoh Corporation

Reply to this Comment

@Sheldon,

No relation to that Nadel... but I too took a Data Structures class :) My professor in that class held the record for the largest baby ever born in his city. Odd what we sometimes know about our teachers.

Reply to this Comment

Hi Ben

Just wanted to say thanks - a couple of your posts I've been reading have been really useful. I've been writing a bit of jQuery to replace textareas and select menus with divs so people can html print forms without them looking awful and having text in textareas hidden by overflow issues.

Cheers

Reply to this Comment

@Ben

Yeah - I like jQuery a lot too, it really takes a lot of the grunt work out writing JavaScript, but of course it does bring its own problems sometimes as you are dealing with an abstraction and its own API.

On the whole though despite their frustrations frameworks like jQuery and CakePHP (which I also use a lot of) are great they can really bring the fun back into coding.

J

Reply to this Comment

Awesome! The regular expression was just what I needed to solve a copy and paste issue I was having with a WYSIWYG.

Thank you
=-)

Reply to this Comment

Thank you! I had been struggling for hours trying to find a PHP way of doing this for a little AJAX Spell checker I'm working on.

It suddenly occurred to me that it was probably easier to just do it with JS in the AJAX function itself.

One google search, a visit to your website and a couple of seconds later and bang. My AJAX spell checker has overcome the newline issue.

Very very helpful. Thank you.

Reply to this Comment

Hi Ben,
The above regular Expression couldn't solve my problem. I want to remove line breaks from following text:
LocationMap.html?16850 SE 272nd Street, Suite 200, Covington,
WA
98042

The resultant data should be:
LocationMap.html?16850 SE 272nd Street, Suite 200, Covington,WA 98042

Thanks
Kalpesh Joshi

Reply to this Comment

Maybe this expl.code will help someone.

<%
var strMulLine=rsP('strMulLine').value.replace(/[\n\r]/g,'\\n');
%>

<SCRIPT LANGUAGE="JavaScript">
var txtTextarea = window.opener.document.getElementById("Textarea1");
txtComments.value = "<%= strMulLine%>";
<SCRIPT>

Thanks Ben for help the "\\n" was my solution.

Reply to this Comment

Sorry this one is corect.
<%
var strMulLine=rsP('strMulLine').value.replace(/[\n\r]/g,'\\n');
%>

<SCRIPT LANGUAGE="JavaScript">
var txtTextarea = window.opener.document.getElementById("Textarea1");
txtTextarea.value = "<%= strMulLine%>";
<SCRIPT>

Reply to this Comment

Hi Ben,
Would like to know can this apply to Oracle PL/SQL??
I got a textarea which I need to control user to key in ONLY 10 rows. How can I count the rows inserted??
Should I use chr(10) & chr(13) or /r/n??

Reply to this Comment

Hi Ben,

Thanks for your response.

But I am sorry to disappoint you that your trick(SomethingText.value.replace(/[\n\r]/g,'\\n')) didn't work.

I will try to elaborate the issue in much simpler way.

var MapURL = LocationMap.html?200%20Auburn%20Ave.%20%20Auburn,%C2%A0WA%C2%A098002;

I guess %C2%A0 is the issue which generates line break and I am really helpless to replace it.

This is the resultant value I get in variable MapURL. When I try to alert the MapURL, the alert message is displayed in following manner:
-------------------------------------------------
LocationMap.html?200 Auburn Ave. Auburn,
WA 98002
-------------------------------------------------

Is there any regular expression or any other method which will fetch below result for var MapURL.

---------------- Expected Result ----------------
LocationMap.html?200 Auburn Ave. Auburn,WA 98002
-------------------------------------------------

Awaiting for your response.

Thanks,
Kalpesh Joshi

Reply to this Comment

@Kalpesh,

You should be able to replace "%C2%A0" with a space in your regular expression:

value = value.replace( new RegExp( "%C2%A0", "g" ), " " )

Reply to this Comment

@Blury,

I would use a regex like "\r?\n|\r" since you don't know where the text is coming from. I believe that different browsers use different line breaks.

Reply to this Comment

Couple of things...

First, I've been typing in or pasting blocks of text from simple notepad text files into a textarea and trying to find a "\r" in it -- completely without success, neither in IE6 nor in any modern browser.
So, for a question, I've got: in what scenario would the dreaded "\r" actually show up in IE6?

Second, here's something that I believe is viable alternative to using regex to strip, or strip and replace, newlines in a long string:

var sample = <some multi-line text block>
var result = sample.split('\n').join(join string) ;

.split(), of course, throws away the split-on string, and bob's yer uncle.

Michael

Reply to this Comment

@Michael,

I am not sure if \r shows up in IE? That might be a FireFox only thing. I know in the past I've had problems with cross-browser line break stuff.

Cool thought on the .join() technique for getting rid of line breaks. Very snazzy!

Reply to this Comment

i only have one question that far outways all the others here...

what happens with Karen and Kimmie next?

Reply to this Comment

I am facing with a issue.
On reading the textarea value in a javascript method the "enter key " is not retrieved.For example if i enter a data

test
test1
test2

on retrieval of the value of this textarea in js it is returned as "test test1 test2" i.e text entered on different lines appear in a single line.

I want to retain the enter key so that my data is visible in the same format as it was entered.

Please help me to get a sollution

Reply to this Comment

@Aaru,

You should get either a new line or a carriage return (or both) in that data. And, if you send that to the server and write it to a file, it should have line breaks in the resultant file.

Chances are, you are trying to output it on a web page, which doesn't respect line breaks / carriage returns. In that case, you need to replace the line breaks with actual <BR> tags.

Reply to this Comment

Thanks Ben.
I had been for days dealing with this issue when sending a textarea content to a database (via php) and then back to an htm page. All these posts have been quite helpful for me.

In regard to your Jan 5 2010 post, I would like just to refresh the reply by Ben (just Ben) of Nov 28 2007:

val = val.replace(/\n/g,"<br/>").replace(/\r/g,"");

A simple and elegant solution for the back and forth of textare contents if you want them as formatted text in the browser.

Wow, Ben Nadel! Your original post is running quickly to its 4th birthday! This is an estimate of its value. Thanks.

Reply to this Comment

@Juan,

Good point for converting back to HTML from the raw text data. I would just be careful about removing the line-return character - I think the different browsers actually use these differently.

Typically, to be safe, I'll use both the \r and the \n in the pattern match:

\r\n?|\n

This way, it will try to match the pattern \r\n first; and, if it can't, then it will alternately match the \r and \n individually.

Reply to this Comment

i try this to output.

<% .
.
.
var typePrjctDetails = rs.fields.item("typePrjctDetails");

typePrjctDetails = typePrjctDetails.replace(/\n/g,"<br/>").replace(/\r/g,"");

.
.
.
%>

but i got error Microsoft JScript runtime error '800a01b6'

Object doesn't support this property or method instead.

Reply to this Comment

@Zhrf,

Is that Javascript? That looks more like ASP (it's been a long time since I've seen that "Record Set" notation.

Reply to this Comment

yes it is. can i use that function for my code? im stuck at this for a week now.sorry if this is not related to your topic.im new at this asp. -_-" thanks in advance ;)

Reply to this Comment

@Zhrf,

Sorry, I haven't used ASP in so long. I didn't even know of regular expressions back then. I cannot be of any help.

Reply to this Comment

Hi Ben,

Thanks for the great blog and for this tip in particular, of course.

I'm writing JavaScript for a PDF form and I needed to test a multi-line field for no value (blank, null), so I needed to strip out the line feeds. Your code worked perfectly for this situation. Thanks a million.

Reply to this Comment

@Tim,

Very cool! If you're just testing for non-empty fields, you could also use the regular expression test() method:

var value = "your field value";

alert(
(new RegExp( "[^\\s]", "" )).test( value )
);

Here, we're testing to see if the given value of the form field matches the given pattern, which is any non-space character (line breaks, tabs, etc). Just another option.

Reply to this Comment

Thanks for your reply, Ben! I've tried to remove the ?, but it doesn't work yet. I can't understand, the syntax seems to me to be right...

Reply to this Comment

Hello Ben,

I am trying to replace linebreaks in a textbox with <br />

and I am using this:

form_content = document.getElementById('description').value;

document.getElementById('ad-desc').innerHTML = replace(form_content,"\n","<br>");

But for some reason it's not working at all!

Any ideas or suggestions why it's not working??

Thanks in advance!

Reply to this Comment

@Abdul,

replace() is not a stand-along method. Is is a class method of the String object. You have to call if ON the string value:

form_content.replace( "\n", "<br>" )

Reply to this Comment

@Ben Nadel,

Hey Ben, thanks for you're response. It works!!

However.. if you could please kindly look at http://edeals.zzl.org/divchange2.php where I am trying it out you will see that with the "description" field... the user must press enter first in order to update the preview div at the top.

Is there anyway around this problem?

Thanks

Reply to this Comment

@Abdul,

Looks like "re_nlchar" is undefined. You don't have an "else" statement in your if-else-if statements; you are hitting a case where none of the conditions in your IF statement are true, causing "re_nlchar" to be undefined. Make sure to cover all of your bases.

Reply to this Comment

Ben, after my test number 57 with a "bug" I came here looking for an answer and I couldn't find it, but, your code and your comments point me to the right direction and the test nÂș 58 was successful (:

Thank you very much!

Reply to this Comment

Hi Ben..
I wanted to avoid the special characters from being entered. To show error message when its entered. So when I press enter it is taken as a special character. So what I did was i had a condition to avoid '\n' in javascript and this is working in Mozilla but not in IE? So can you please try to get a solution..

Reply to this Comment

Geez!!! What's with the X-rated sample text!? Stuff like that fscks me up when I'm trying to work.

Good article though. Thx.

Reply to this Comment

this statement:
Textarea values might have the character combos "\n\r" in the text box, but once they are pulled into Javascript, "\n\r" becomes JUST "\n"

Is entirely wrong in Chrome, and Chrome turns it to: \r\n.

Reply to this Comment

sorry I lied, apparently that was IE, so far can't get Chrome to work at all.

Reply to this Comment

Hello Ben,

I've got a ridiculous problem in replacing two or more instances on a single line.

I am using the following text:

Hello, %%User.Firstname%% %%User.Lastname%%,
blah blah blah
Your links;
%%attachments_html%%

Regards,
%%My.Firstname%%

---

The code to replace this is as follows:

var text = $('#composer').text();

var rePattern = new RegExp('%%([a-z_]+[\.[a-z_]+]?)%%','mgi');

while(match = rePattern.exec(text)) {

console.log(match, MailBuilder.findPlaceHolder(match[1]));

text = text.replaceAll(match[0], MailBuilder.findPlaceHolder(match[1]));

}

(findPlaceHolder is a function later in the script, removed for simplicity.)

It will replace everything but the %%User.Lastname%% part. The wierd thing is if I remove the replaceAll() method it returns the requested information fine to Firebug.

I am so very confused. Can you suggest anything I might have overlooked?

Many thanks,
Tom H

Reply to this Comment

@Tom,

I am not sure that your regular expressions is correct. It looks like you have a character class where you might want a capturing group. You hvae:

RegExp('%%([a-z_]+[\.[a-z_]+]?)%%','mgi')

... and I think you want:

RegExp('%%([a-z_]+(\.[a-z_]+)?)%%','mgi')

Also, I am not sure what the replaceAll() method is that you are calling.

Reply to this Comment

Hey Ben

Great post...however, I am using a javascript to report back how many characters remaining the user has on the text box.

Problem is that LINE FEEDS in the javascript are counting back as only ONE character, and Cold Fusion reports the length it seems counting the "\n" as two characters.

Any comment on how to get the javascript to count as two characters to the user?

Here is the Javascript:

function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}

Reply to this Comment

@Reticon,

From now on, I just use the optional pattern for line breaks that includes all the possible combinations:

(\r\n?|\n)

... this seems to take care of all the possible environmental flavors that I've run into.

@Michael,

If ColdFusion treats the line breaks (probably chr( 13 ) + chr( 10 )) as two characters then, the easiest solution in Javascript might be to replace the line breaks with two characters when counting the length. Example:

yourValue.replace( new RegExp( "\\r\\n?|\\n", "g" ), ".." ).length

This way you normalize the number of characters across browsers... I think.

Reply to this Comment

How can i replace only soft line break with space and maintain the hard line break in a text using regex.
I tried replace(/(\r\n){2,}/g,'\n') and later
replace(/\n/g,' ') but without success.

Reply to this Comment

Let me make clear...
I have got a plane text in the format like
-------------------------------------------
text text text
text text texttext text text
text text text

text2 text2 text2
text2 text2 text2

You can see there is a line break in between the two paragraph so i want the text in the two paragraph seperated by a space one after another but maintaining the black line break between them.

Desired result
-----------------------------
text text text text text texttext text text text text text

text2 text2 text2 text2 text2 text2

How can i do this using regex and javascript i have tried replacing the line break with space but it removes all the line break even the seperation line break.

Reply to this Comment

Hi Ben,

I want to convert two or more line breaks into one line break. Is there any reqular expression?

this one is not working
strMultiLineText1.replace(new RegExp("[\n\n]", "g" ), "\\n);

Given Text
------------
Line 1
<linebreak1>
<linebreak2>
Line 2
<linebreak1>
<linebreak2>
<linebreak3>
Line 3

Expecting Result
Line 1
<linebreak1>
Line 2
<linebreak1>
Line 3

Reply to this Comment

@Gaurab,

Hmm, that one is kind of stumping me. I think you'd have to have negative look-behinds for this; but, Javascript doesn't allow for those. I am not sure what to say.

@Kaman,

Unlike @Gaurab, this direction is a bit easier. Trying something like this:

yourValue.replace(
new RegExp( "(\\r\\n?|\\n)\\1+", "g" ),
"$1$1"
);

... this replace all 2+ line breaks with exactly two line breaks.

Reply to this Comment

hi ben,

i tried your code before sending the data to a php file using ajax and still newline is not recognized... any suggestions?

thanx!

Reply to this Comment

@Lexus,

Try looping over all the characters in your string on the PHP side and outputting the ASCII value. You're probably looking for a chr 13 / 10. See if either of those show up.

Reply to this Comment

@Lexus,

Glad you got it sorted - what was the problem? How come the new lines weren't showing up in your PHP?

Reply to this Comment

@Ben,
i've done a little research on it and all resources pointed out to the problem with textarea. newline is disregarded or something like that. i've tried the codes i've made a few months ago in php and i countered the same problem. so what i did was, in my javascript i used the replace() funtion before sending it to be processed by php.

Reply to this Comment

@Ben

Hi, this is not solving the problem I am running into. When I try to do a replace for the line feed, I get the error "Unterminated string constant". The string already has the line feeds, so it won't allow me to read it.
Here is my code:

function removeBR()
{
try
{
var str = '@Selected Medical Questions@';
str = str.replace(new RegExp( '\\n', 'g' ), ' ... ');
alert(str);
}
catch(err)
{
alert('Error: Javascript for Med Questions - web_page_view:' + err.description);
}
}

@variableName@ is the field that I am trying to output that is read froma database. I get no errors if I get rid of the str = str.replace
line of code.

Any help would be great, I am at my whits end!

Reply to this Comment

@Ian,

If your database value has an apostrophe in it, it will break your string value. You need to escape the apostrophe. For example, in ColdFusion, you could do something like this:

var str = '#JSStringFormat( @Selected Medical Questions@ )#';

... your language of choice probably has something similar.

If that is not the problem, I am not sure what else it could be.

@Suraj,

Awesome :)

Reply to this Comment

@ Ben
I did solve the problem. I could not do a string replace, and because of the platform, I cannot use Coldfusion. I wish I could. The work around was accually simple. All I had to do was instead of inserting the text into a textarea or textbox. I just had to insert the 'so called string' directly into the div tag without the textarea or textbox. Strange, but it worked.
Thank you for your help!

Reply to this Comment

@Ian,

I am not sure if putting it in the DIV actually removes the line breaks; I think it simply doesn't render them (HTML doesn't render line breaks). Perhaps I'm just not understanding what's actually working. In any case, I am glad you got it working.

Reply to this Comment

Hello Ben,
I really appreciate you for helping every body on this posts. I actually went over all the posts here but still I am not able to get what i want.If possible plz help me out.

I am using javascript in my aspx page. Now I am getting a text value in session variable which has new line and also might have double quotes in it. So I am trying to get overcome this new line and trying to maintain the double quotes...
I am writing like this:

var SessionVar = "<%=replace(replace(Session("Notes"),"\n","\\n"),"""","\""")%>"

Problem :
Above line gives error as it is unable to remove new line chars.

Also here I cant use like this:
str.replace () cause I am getting value from Session variable...so I am using above format...

If I only write as below to remove double quotes then it works fine:
var SessionVar = "<%=replace(Session("Notes"),"""","\""")%>"

but if the Notes contain new line then it will throw error...So I have to write replace statement such that at the SAME time I will have to remove new line and double quotes..

Plz help me to get over this...your arduous efforts would be much appreciated...

thanks in advance..

Reply to this Comment

You saved my live for not wasting another 2 hours again figuring this new line stuff.

Just hoping that this "THANK YOU" can appreciate all of your writings about this "\n".

And again,
THANK YOU

Reply to this Comment

@Ferde, @Maghdalena, @UncleNinja, @Chary,

No problem guys - always glad this helps people.

@Vicky,

I don't much about ASP(.NET), which is looks like you are using. Perhaps the problem is which the way .NET handles back-slashes in strings. Is it possible that they are not special characters? For example, in ColdFusion, "\n" in a string doesn't actually mean anything more than the literal string (back-slash followed by n). It is only within a *regular expression* that the \n pattern is useful.

If .NET didn't treat the backslash as anything special, it would explain why your replace statement is not finding anything to replace.

Reply to this Comment

What "Topper" said about newlines is not quite true; I also always believed it was "\r\n" and under Windows "\n", but Topper is probebly just like me from a Unix world. In Unix its "\r\n" but under Windows, it can indeed also be "\n\r". It all depends if your under Windows, Unix or Mac. I found out myself just a couple of days ago, I had spend hours of swearing why I couldn't grep my newline line in php. Then I changed the grep to "\n\r" and all over the sudden it took it. So I now always take all three into account, "\n", "\r\n" and "\n\r" = safest way.

Reply to this Comment

I get error: "Object doesn't support property or method 'replace'

try
{
alert(branchValueControl.value);
branchValueControl = branchValueControl.value.replace(new RegExp('\\n', 'g'), '...');
alert(branchValueControl.value);
}
catch(err)
{
alert(err.description);
}

Any ideas?
Thank you

Reply to this Comment

@Maximus,

Sounds like the "value" object isn't really a String. What happens if you alert:

typeof( branchValueControl.value );

Reply to this Comment

Ben,

I get the following:

//String
alert(typeof(branchValueControl.value));
Object
alert(typeof(branchValueControl));

and just correcting my typo above:

branchValueControl = branchValueControl.replace(new RegExp('\\n', 'g'), '...');

Not sure why I get the error
Thanks

Reply to this Comment

Ben,

Solution:
branchValueControl.value = branchValueControl.value.replace(new RegExp("\\n", "g"), "...");

Thanks

Reply to this Comment

Hi Ben,

Just wanted to let you it might have already been mentioned but line breaks are treated different in fire fox then they are in IE with javascript. Example if you have a text area box and you type in text if you put a hard return fire fox treats it as '\n' which is just one character and IE treats it as '\n\r'.

Reply to this Comment

Below is my javascript code:

string script = "window.setInterval(\"if(confirm('Session has been idle over its time limit.Press Ok now to conitnue session.')){} else {window.location.href = '/Logout.aspx';} ;\", " + (Session.Timeout - 5) * 60000 + " )";

Now i need to break a line between 'Session has been idle over its time limit' and 'Press Ok now to conitnue session'.
I have tried \n, \r\n, \\r\\n, \\n, \r and lots of same type but not getting right answer.

Have you any idea on the same.

Many Thanks.

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.