skip to Main Content

I have a string like this:

`Name: XYZ
Age: 28

Email: [email protected]
Department: Test`

How can I convert this to JavaScript object like:

{Name: 'XYZ', Age: '28', Email: '[email protected]', Department: 'Test'}

2

Answers


  1. function parseStringToObject(inputString) {
       const regex = /(w+): (S+)/g;
       let match;
       const result = {};
    
       while ((match = regex.exec(inputString)) !== null) {
          result[match[1]] = match[2];
       }
    
       return result;
    }
    
    const inputString = "Name: XYZ Age: 28nEmail: [email protected] Department: Test";
    const resultObject = parseStringToObject(inputString);
    
    console.log(resultObject);
    

    The following Code should work fine for you

    Login or Signup to reply.
  2. Use split to get an array of lines, then filter out empty lines. Finally, use split on each line to get the key and value, and use Object.fromEntries to turn key-value pairs into an object.

    let s = `Name: XYZ
    Age: 28
    
    Email: [email protected]
    Department: Test`
    
    let r = Object.fromEntries(s.split('n').filter(s=>s).map(s=>s.split(': ')))
    
    console.log(r)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search