5
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.

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

That's because you are actually evaluating code that looks like this, which is ofcourse wrong in javascript

​var test = "Lorem ipsum
    dolor sit amet"; ​​​​​​​​​​​​​​​​​

Why do you need the eval? It looks not really necessary in this case. Maybe we can help you get around the eval?

Comments

0

Try:

   const address = document.getElementById('address').value
   eval('input = ' + JSON.stringify(String(address)))

String(address) will guarantee that the object is a string. JSON.stringify will return a double quoted string parsable with eval.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.