开发者

Javascript Strings don't compare, escape characters not being escaped when using jQuery.val() func

开发者 https://www.devze.com 2022-12-17 03:57 出处:网络
I have: <input t开发者_如何学JAVAype=\"text\" value=\"Raphaël\\nkicks\\nbutt!\" id=\"tzbox_txt\">

I have:

<input t开发者_如何学JAVAype="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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号