I have a string that represents an array. How can I push an element keeping the format?

by Leandro   Last Updated September 11, 2019 19:26 PM - source

I have this string:

"""
const arr = [
  CustomClass1,
  CustomClass2,
  CustomClass3,
  CustomClass4,
  CustomClass5
];
"""

I want to add to that string CustomClass6 (names can vary) in order to have a string like the following:

"""
const arr = [
  CustomClass25,
  CustomClass9,
  CustomClass12,
  CustomClass8,
  CustomClass2,
  CustomClass6
];
"""

I managed to accomplish it, but it does not work when the array looks like this one:

"""
const arr = [CustomClass10, CustomClass6];
"""

Or if it looks like this:

"""
const arr = [CustomClass5]
"""

The problem is I need to keep the format. These are the functions until now. As you can see, I have hardcoded the separator to be \n:


function getStringWithElementAppended(
  stringWithArray: string,
  classToAppend: string
) {
  const openingBraketIndex = stringWithArray.indexOf('[');
  const closingBracketIndex = getIndexInString(
    stringWithArray,
    ']',
    openingBraketIndex
  );

  const updatedContent = appendElementToArrayInString(
    classToAppend,
    openingBraketIndex,
    closingBracketIndex,
    stringWithArray
  );

  return updatedContent;
}

function getIndexInString(
  String: string,
  stringToLookFor: string,
  startingIndex: number = 0,
  limitIndex: number = String.length,
  lastIndex = false
) {
  const auxString = String.slice(startingIndex, limitIndex);

  if (lastIndex) {
    return startingIndex + auxString.lastIndexOf(stringToLookFor);
  } else {
    return startingIndex + auxString.indexOf(stringToLookFor);
  }
}

function appendElementToArrayInString(
  elementToAppend: string,
  arrayBeginingIndex: number,
  arrayEndIndex: number,
  String: string
) {
  const separationBetweenElements = '\n';
  const endOfArrayIndex = getIndexInString(
    String,
    separationBetweenElements,
    arrayBeginingIndex,
    arrayEndIndex,
    true
  );
  const previousElementEndIndex = getIndexInString(
    String,
    separationBetweenElements,
    arrayBeginingIndex,
    endOfArrayIndex,
    true
  );
  const spaceBetweenElements = String.slice(
    previousElementEndIndex + 1,
    endOfArrayIndex
  );
  const whitespaceIndex = spaceBetweenElements.lastIndexOf(' ');
  const whitespace = spaceBetweenElements.slice(0, whitespaceIndex + 1);
  const contentToAdd =
    ',' +
    separationBetweenElements +
    whitespace +
    elementToAppend +
    separationBetweenElements;
  const updatedString =
    String.slice(0, endOfArrayIndex) + contentToAdd + String.slice(arrayEndIndex);
  return updatedString;
}

What I need specifically is to get the separator between the elements. Either \n, or nothing, and if there is whitespace, or not, as the following cases should be valid:

"""
const arr = [];
"""

"""
const arr = [CustomClass34];
"""

"""
const arr = [CustomClass8,CustomClass76];
"""

I am SURE someone must have done it before. I know it is not that difficult to come up with, but if someone knows where to look for it, it would be amazing.

The final result should be: A function that given any of the above examples, and the name of a class, it should add to the array the class, but keeping the format.

For example:

Given CustomClass2 and a string:

"""
const arr = [
  CustomClass25,
  CustomClass9,
  CustomClass12,
  CustomClass8
];
"""

It should return the following string:

"""
const arr = [
  CustomClass25,
  CustomClass9,
  CustomClass12,
  CustomClass8,
  CustomClass2
];
"""

But it should work either if there is one element in the array, none, or N elements without whitespace between them.



Answers 2


I am not sure whether the following will help you, still give it a try. The only issue you might face is having duplicate entries in the array, if you push it when it already exists.

let data=`"""
const arr = [
  CustomClass1,
  CustomClass2,
  CustomClass3,
  CustomClass4,
  CustomClass5
];
"""`;
let newData="CustomClass6";
let InsertionPointPart=data.match(/(\n)+( )*]( )*;/g)[0];
//The InsertionPointPart is
//
//];
data=data.replace(InsertionPointPart,",\n  "+newData+InsertionPointPart);

console.log(data);

// """
// const arr = [
//   CustomClass1,
//   CustomClass2,
//   CustomClass3,
//   CustomClass4,
//   CustomClass5,
//   CustomClass6
// ];
// """
Rohith K N
Rohith K N
September 11, 2019 19:15 PM

Just replace the terminating syntax of the array with a new ending piece that contains your new string.

const input = 
`"""
const arr = [
  CustomClass25,
  CustomClass9,
  CustomClass12,
  CustomClass8
];
"""`;
console.log(input);

const pushVal = 'CustomClass5';

function stringPush(val,stringArray){
 return stringArray.replace('];','  ' + val + ',\n\;');
}

console.log(stringPush(pushVal,input));

Travis J
Travis J
September 11, 2019 19:25 PM

Related Questions


How to replace symbol to letter

Updated October 08, 2017 09:26 AM


Retrieve subset of string Javascript

Updated December 13, 2016 08:11 AM

replace . with a ~ using javascript

Updated July 18, 2017 04:26 AM