Convert array cells based on quote character that wraps cells

Viewed 41

I have an array like this a=['"nam', 'e"', '"numb', 'er"']. I want to create another array based on this array's cells. if the cell starts with a quote, then track the next cell that ends with a quote and declare that a cell for the new array. here's an example of how the array will become after conversion:

converted_array=['name', 'number']

Keep in mind that the array might be in this format

a=["'name", "e'", "something", "'numb", "er'"]

Any ideas?

2 Answers

Check this code

const myArr = ['"My', 'Number"', 'hello', '"text--', '12345"'];

let result = [];
let status = 0;
for (let i = 0; i < myArr.length; i++) {
  let r = myArr[i];
  if (r[0] == "'" || r[0] == '"') {
    result.push(r.slice(1));
    status = 1;
  } else if (r[r.length - 1] == "'" || r[r.length - 1] == '"') {
    result[(result.length - 1)] += "" + (r.slice(0, -1));
    status = 0;
  } else if (status == 1) {
    result[result.length - 1] += (r);
    status = 1;
  } else {
    result.push(r);
    status = 0;
  }
}

console.log(result);

Check this out

const myArr = ["'My", "Nu'mber", "hello'", "text--'", "12345'hou", "se'"];

const result = []
const delimiter = "'"
let closing = false
let tempText = ''
for (const item of myArr) {
  if (!closing) {
      if (item.startsWith(delimiter)) {
        tempText += item
        closing = true
      } else {
        result.push(item)
      }
  } else {
      tempText += item
      if (item.endsWith(delimiter)) {
        result.push(tempText)
        tempText = ''
        closing = false
      }
  }
}

console.log(result);

Related