0

I have a string like this ,where first value is state and other value is its capital, I want to convert this string in array using javascript/jquery and spaces between strings is included.

"[['Congo' , '"Candice Levy"'],['Panama' , '"Xerxes Smith"'],['Tanzania' , '"Levi Douglas"'],['africa' , '"Uriel Benton"'],['Gabon' , '"Celeste Pugh"'],['Syrian' , '"Vance Campos"'],['Kyrgyzstan' , '"Wanda Garza"']]

my expected output like this

arr[0]= Congo
arr[1]= Candice Levy
arr[2]= Panama
arr[3]=Xerxes Smith

I have seen some example like this, but did not get any satisfied answer.please help

4
  • 3
    You have share the input array, please provide the expected output array as well. Commented Jul 3, 2017 at 6:21
  • Do you mean you want to convert string to array? Commented Jul 3, 2017 at 6:21
  • @RaxWeber: yes i want to covert string to array Commented Jul 3, 2017 at 6:30
  • your input actually is a json string of a 2-dimension array and you want to convert it into a 1-dimension array, right? Commented Jul 3, 2017 at 6:35

5 Answers 5

1

**EDIT : ** Thanks to shaochuancs's comment.

var str = "[['Congo' , '\"Candice Levy\"'],['Panama' , '\"Xerxes Smith\"'],['Tanzania' , '\"Levi Douglas\"'],['africa' , '\"Uriel Benton\"'],['Gabon' , '\"Celeste Pugh\"'],['Syrian' , '\"Vance Campos\"'],['Kyrgyzstan' , '\"Wanda Garza\"']]";

var str = str.replace(/'/g,'"').replace(/""/g,'"');
var arr = JSON.parse(str);
var merged = [].concat.apply([], arr);

console.log(merged);

var arr = [['Congo' , '"Candice Levy"'],['Panama' , '"Xerxes Smith"'],['Tanzania' , '"Levi Douglas"'],['africa' , '"Uriel Benton"'],['Gabon' , '"Celeste Pugh"'],['Syrian' , '"Vance Campos"'],['Kyrgyzstan' , '"Wanda Garza"']];

/********Using foreach*****************/
var newArray = [];
arr.forEach(function(ele) {
  ele.forEach(function(d) {
    newArray.push(d);
  });
});
//console.log(newArray);

/**********Using concat*********************/
var merged = [].concat.apply([], arr);
//console.log(merged);

var result = []
merged.forEach(str => result.push(str.replace(/"/g, "")));
console.log(result);

You can use the following method to remove \" from string

var result = []
merged.forEach(str => result.push(str.replace(/"/g, "")));
Sign up to request clarification or add additional context in comments.

1 Comment

please note OP need to convert String to array. So the arr object in the code snippet need to be generated first :)
0

What I understood is this: You have a string like what you have provided. You want it to be converted to an array like you have mentioned in your question (edited). This does the job:

function showInput(){
    var str = "\"[['Congo' , '\"Candice Levy\"'],['Panama' , '\"Xerxes Smith\"'],['Tanzania' , '\"Levi Douglas\"'],['africa' , '\"Uriel Benton\"'],['Gabon' , '\"Celeste Pugh\"'],['Syrian' , '\"Vance Campos\"'],['Kyrgyzstan' , '\"Wanda Garza\"']]";
    var res = str.split(",");
    var array = [];
    for (var i=0; i<res.length; i = i + 2){
        array[i] = res[i].substring(res[i].indexOf("'")+1,res[i].lastIndexOf("'"));
        array[i+1] = res[i+1].substring(res[i+1].indexOf('"')+1,res[i+1].lastIndexOf('"'));
    }
    //array variable has what you require
    alert(array.join());
}

What I am doing is I am first splitting everything by a comma and putting it into an array called 'array'. Now, I iterate in bunch of twos (because we have a pair, the state followed by the capital). For each state, we simply have to get the substring between the single quotes. For each capital, we simply need the substring between the double quotes.

Comments

0

You can use regular expression to replace the "[,],\" with '', then use split method to the replace result.

var obj = [
    [
        "Congo",
        "\"Candice Levy\""
    ],
    [
        "Panama",
        "\"Xerxes Smith\""
    ],
    [
        "Tanzania",
        "\"Levi Douglas\""
    ],
    [
        "africa",
        "\"Uriel Benton\""
    ],
    [
        "Gabon",
        "\"Celeste Pugh\""
    ],
    [
        "Syrian",
        "\"Vance Campos\""
    ],
    [
        "Kyrgyzstan",
        "\"Wanda Garza\""
    ]
];
var expectVal = JSON.stringify(obj).replace(/[\\\"\[\]]/g, '').split(",");

Comments

0

Here is an example using String split:

'use strict';

var s = "[['Congo' , '\"Candice Levy\"'],['Panama' , '\"Xerxes Smith\"'],['Tanzania' , '\"Levi Douglas\"'],['africa' , '\"Uriel Benton\"'],['Gabon' , '\"Celeste Pugh\"'],['Syrian' , '\"Vance Campos\"'],['Kyrgyzstan' , '\"Wanda Garza\"']]";

var arr = s.split(/]\s*,\s*\[/);

var resultArr = [];
for (var i in arr) {
  var stateAndCap = arr[i];
  var stateAndCapArr = stateAndCap.split(/\s*,\s*/);

  var state = stateAndCapArr[0].split('\'')[1];
  var cap = stateAndCapArr[1].split('"')[1];
  resultArr.push(state);
  resultArr.push(cap);
}

console.log(resultArr);

Comments

0

We may solve it by split the entire string by comma operator then remove the unwanted symbols from each string.

    var str = "[['Congo' , '\"Candice Levy\"'],['Panama' , '\"Xerxes Smith\"']]";
    var stringArray = str.split(",");
    var result = [];
    for(var i = 0; i < stringArray.length; i++){ 
        result[i] = stringArray[i].replace(/[^a-z0-9\s]/gi,'').trim(); 
    }
    console.log(result);

1 Comment

To avoid forloop use underscore.js map function to iterate the loop with more efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.