An example of the conversion of string and object in JS

Source: Internet
Author: User
Tags eval


Cases

The code is as follows Copy Code

The string to object//eval () function computes a string and executes the

JavaScript code.

var str= "var data= ' Am I a string or an object? '"
eval (str);
Console.log (data); Object to String

var obj=function () {
Console.log ("Am I an object or a string?");
}
Console.log (Obj.tostring ());

With spaces and line breaks
Console.log (Obj.tostring (). replace (/[rn,]/g, ""));

No spaces and line breaks

Cases

Object Turn Stirng

The code is as follows Copy Code


function Obj2str (o) {
var r = [];
if (typeof o = = "string" | | | o = = NULL) {
return o;
}
if (typeof o = = "Object") {
if (!o.sort) {
R[0]= "{"
for (var i in O) {
R[r.length]=i;
R[r.length]= ":";
R[r.length]=obj2str (O[i]);
R[r.length]= ",";
}
R[r.length-1]= "}"
}else{
R[0]= "["
for (var i =0;i<o.length;i++) {
R[r.length]=obj2str (O[i]);
R[r.length]= ",";
}
R[r.length-1]= "]"
}
Return R.join ("");
}
return o.tostring ();
}

String to Object

  code is as follows copy code

function Taoran () {
var str= ' {' result ': [['] 219 "], [" Bank "," 121 "], [" Refund "," 272 "], [" Failed to mention "," 16 "], [" Group purchase "," 15 "], [" Taobao "," 41 2 "],[" "Taiwan", "58"], ["Present Limit", "16"], ["Time To Date", "81"], ["Taiwan Certification", "26"]]} ';
Alert (strtoobj (str). Result[2]);
}

Function strtoobj (JSON) {
         return eval ("+json+") );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.