2

I have this string.

'"pen pineapple" apple pen "pen pen"'

Is there a good way to convert it into an object which would look like this:

{
a: "pen pineapple",
b: "apple",
c: "pen",
d: "pen pen"
}

I am looking for a solution in pure javascript!

utkarsh tyagi
  • 635
  • 1
  • 9
  • 27

4 Answers4

2

Splitting strings that have quotes...

https://stackoverflow.com/a/18647776/2725684

Then converting that array into an object...

https://stackoverflow.com/a/4215753/2725684

So, when you combine these answers, it looks like this...

var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = '"pen pineapple" apple pen "pen pen"';
var myArray = [];

do {
    var match = myRegexp.exec(myString);
    if (match != null) {
        myArray.push(match[1] ? match[1] : match[0]);
    }
} while (match != null);

var obj = myArray.reduce(function(acc, cur, i) {
  acc[i] = cur;
  return acc;
}, {});

console.log(obj);
Community
  • 1
  • 1
Waxi
  • 1,641
  • 2
  • 14
  • 20
1

You could use an adapted version of Split a string by commas but ignore commas within double-quotes using Javascript and use Number#toString method for the keys.

var str = '"pen pineapple" apple pen "pen pen"',
    arr = str.match(/(".*?"|[^" \s]+)(?=\s* |\s*$)/g),
    object = {};

arr.forEach(function (a, i) {
    object[(i + 10).toString(36)] = a.replace(/"/g, '');
})    

console.log(object);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This might not be the most efficient function but does what you need (returns array)

function splitter(inputString) {
    var splitted = inputString.split(' ');
    var out = []
    var temp = "";
    var quoteStarted = false;

    for (i = 0; i < splitted.length; i++) {

        if (splitted[i].indexOf('"') > -1 && !quoteStarted) {
            temp += splitted[i] + " ";
            quoteStarted = true;
        } else if (quoteStarted && splitted[i].indexOf('"') == -1) {
            temp += splitted[i] + " ";
        } else if (quoteStarted && splitted[i].indexOf('"') > -1) {
            temp += splitted[i];
            out.push(temp);
            quoteStarted = false;
            temp = "";
        } else {
            out.push(splitted[i])
        }
    }
    return out;
}
pranavjindal999
  • 2,937
  • 2
  • 26
  • 35
0

It can be achieved in pure javascript like this way

let str = '"pen pineapple" "apple" "pen" "pen pen"'
let obj = {}
let pattern = /".*?"/g;
let index = ["a","b","c","d","e"]
let i=0
let key

while(current = pattern.exec(str))
 {
   key = index[i]
   obj[key] = current[0].replace('"','')
   i++
 }

console.log(obj)