Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

Javascript - Convert string with comments to object

how can i change following string to Object?


"password: {
  minLength: 8, // some comments
  maxLength: 24,
  strong: (value) => /.*[^0-9]+.*[0-9]+.*|.*[0-9]+.*[^0-9]+.*/.test(value),
},"
question from:https://stackoverflow.com/questions/65851951/javascript-convert-string-with-comments-to-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If -- and only if -- this string is under your control, and not that of a user of your application, you can use eval. Note that some changes are needed, as the string contents do not represent valid JavaScript, it seems to be an object with a password property, but the surrounding braces are missing.

So here is how it could work:

let input = `password: {
  minLength: 8, // some comments
  maxLength: 24,
  strong: (value) => /.*[^0-9]+.*[0-9]+.*|.*[0-9]+.*[^0-9]+.*/.test(value),
},`;

// Add braces to make it a valid object literal, and
// add parentheses to make it into an expression:
let result = eval(`({${input}})`);
console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...