Reputation: 2722
Let's say I have the String
representation of a String
literal (with escape characters and all); written out as a literal itself, it could look like:
'\'Hello,\\tI'm tabbed over!\\n\''
How do I internalize this as a String
, equivalent to the String
represented by the literal in String
form; that is, equivalent to what I would get if I just typed
'Hello,\tI'm tabbed over!\n'
into a program?
I'm aware that I could just use eval()
, but that seems like a terrible solution. I could be using eval()
to convert numeric literals in string form to actual numbers, but there are already functions like Number.parseInt()
for that purpose. Is there anything like this for String
s?
Upvotes: 0
Views: 160
Reputation: 5253
Try this:
var toConvert = "\'Hello,\\tI'm tabbed over!\\n\'";
var str = (new RegExp(toConvert)).toString().replace(/^\/|\/$/g,'');
console.log(str) // 'Hello,\tI'm tabbed over!\n'
update
There is a much easier solution:
"'\'Hello,\\tI'm tabbed over!\\n\'".toString()
Upvotes: 1