最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论
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.

发布评论

评论列表(0)

  1. 暂无评论