Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to escape special characters within eval using javascript?

var input;

// method 1
input = document.getElementById('address').value;
alert(input)

// method 2
eval('input = "'+document.getElementById('address').value+'"')
alert(input)

method 1 is working fine, but method 2 is not working when newline characters are inputted and it says "unterminated string literal".

I need to store values using eval anyway. So please help me.

like image 543
A.N.M. Saiful Islam Avatar asked Sep 30 '10 11:09

A.N.M. Saiful Islam


People also ask

How do you escape a special character in JavaScript?

To use a special character as a regular one, prepend it with a backslash: \. . That's also called “escaping a character”.

Can I escape HTML special chars in JavaScript?

String − We can pass any HTML string as an argument to escape special characters and encode it.

How do you escape special characters?

Special characters can serve different functions in the query syntax. To search for a special character that has a special function in the query syntax, you must escape the special character by adding a backslash before it, for example: To search for the string "where?", escape the question mark as follows: "where\?"

How do you escape from STR?

In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.


1 Answers

Use string.replace(/\r?\n/g, "\\n") to escape the newlines.

like image 150
Aaron Digulla Avatar answered Oct 04 '22 00:10

Aaron Digulla