Remove Quoted Character

by amindunited

JavaScript

const csv = `value 1, value 2, "in quotes, with comma", value after, "another set, with them", value last`;

const getNthPosition = (sourceString, searchString, nthIndex) => {
  return sourceString.split(searchString, nthIndex).join(searchString).length + 1;
}

/**
 * Replaces every occurance of given character that is between quotes in a given string
 * ...(it also removes the quotes)
 */
const replaceQuotedCharacter = (source, character, replacementString)  => {
  let start, end, finalString;

  finalString = source;

  // If there are any quotes left clean up
	if (source.indexOf('"') >= 0) {
  	const startingIndex = source.indexOf('"');// The index of the first quotation mark
    const endingIndex = getNthPosition(source, '"', 2);// The index of the second quotation mark
  	const quotedString = source.substring(startingIndex, endingIndex);// The part of the string that is in quotes
    let unQuotedString = quotedString.replace(/"/g, '');
    	unQuotedString = unQuotedString.replace(character, replacementString);// ','
    finalString = source.replace(quotedString, unQuotedString);
  }


  if (finalString.indexOf('"') >= 0) {
  	return replaceQuotedCharacter(finalString, character, replacementString);
  } else {
  	return finalString;
  }

};

const cleaned = replaceQuotedCharacter(csv);
console.log('cleaned ', cleaned);