how to escape special characters within eval using javascript? - Stack Overflow

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

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.

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.

Share Improve this question asked Sep 30, 2010 at 11:38 A.N.M. Saiful IslamA.N.M. Saiful Islam 2,1387 gold badges28 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

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?

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744018775a4544475.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信