views:

292

answers:

3

I have:

<input type="text" value="Raphaël\nkicks\nbutt!" id="tzbox_txt">

var inputText = $("#tzbox_txt").val(); 
var stringText = "Raphaël\nkicks\nbutt!"
inputText === stringText - false!

If I use $(input).val() I get "Raphaël\nkicks\nbutt!" where \n is not being interpreted as line breaks. And if I do var text = "Raphaël\nkicks\nbutt!" it is being escaped and text shows with line breaks.

How do I make input text value to be interpreted with line breaks?

+1  A: 

An input[type=text] element cannot contain line breaks because the text input only accepts a single line of text. What you think of as newline escape sequences are being interpreted as plain text.

If you wanted to match it, change your matching code to this because this is exactly what is being returned from the val() function:

var stringText = "Raphaël\\nkicks\\nbutt!";

If you wanted to match it the other way around, and your input elements contain the text sequence of '\n' you could do a replace on the text value before testing:

var inputText = $("#tzbox_txt").val().replace(/\\n/g,"\n");
var stringText = "Raphaël\nkicks\nbutt!";
inputText === stringText; // true
Doug Neiner
this will match, but my question was if there is a way to interpret text from textbox value with line breaks?
McLovin
@mercury22 I updated my answer to work the other way around, but be aware, *whatever you do* it will be a workaround or hack. `input` elements cannot contain multiline text in the native sense.
Doug Neiner
+2  A: 

If you want multiline text input you should be using textareas not input text boxes. Text boxes are only a single line of text so no newlines.

Edit: if you want to treat the sequence \n as a newline do a search and replace:

var s = "this\\nis\\na\\ntest";
var unescaped = s.replace("\\n", "\n");

What you have in the string is a backslash literal followed by an n. This search and replace replaces the literal "\n" with a newline.

cletus
I do want multi line text, but it needs to be interpreted from the textbox. My question was if there is a way to interpret text from textbox value with line breaks?
McLovin
@mercury22: you can do a simple search and replace for that (as per edited answer).
cletus
thanks Cletus I've upvoted your answer but Doug was earlier with the search and replace
McLovin
A: 

I think the essential problem here is that, in the input textbox \n is being interpreted as backslash and the letter n, whereas in the var statement the \n is being converted into an actual line break.

Robert Harvey