ppppp
ppppp

Reputation: 229

add/remove text multiple line for javascript

I have the multiple line string which need to remove/add here's the data that I would like to edit

  data{
      id
      date
      ***progress{
        update
        progressStatus
      }***
      events {
        id
        time
      }
    }

my point is how do I remove

progress{
            update
            progressStatus
          }

I had tried 'replace', 'assign' to remove it as below but not working

  const test = data.replace(progress, '');

Thank you.

Upvotes: 2

Views: 234

Answers (3)

Prawin soni
Prawin soni

Reputation: 452

Here's the logic, I'm considering that you want to remove the "progress" which has an open curly bracket('{') and a closing curly bracket('}'):

var data = `data{
      id
      date
      ***progress{
        update
        progressStatus
      }***
      events {
        id
        time
      }
    }`;
function _remove(data, key) {
  var s = data.indexOf(key);
  var e = ((s) => {
    for(var i=s; i<data.length; i++){
      if(data[i] == "}")
        return i;
    }
  })(s + key.length);
  console.log(data.replace(data.substr(s, e-s+1), ""));
}
_remove(data, 'progress');

Can be done with regex as well!

Upvotes: 1

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

You could try with a regexep

enter image description here

const regex = /progress{[^}]+}\s+/gm;
const str = `data{
      id
      date
      progress{
        update
        progressStatus
      }
      events {
        id
        time
      }
    }`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Upvotes: 0

thortsx
thortsx

Reputation: 2280

What is I have the multiple line ? The query of grapqh will return an object, why still a multiple string ?

In your case (the query data is a string), try:

const data = ` data{
      id
      date
      progress{
        update
        progressStatus
      }
      events {
        id
        time
      }
    }`
const newData = data.replace(`progress{
        update
        progressStatus
      }`, '')
console.log(newData)

If you want to delete one key in object, try this:

delete data.progress;

// or,
delete data['progress'];

// or,
const prop = "progress";
delete data[prop];

Demo:

const data = {
       progress: {
          x: "x"
       },
       events: {
          id: 1
       }
    }

delete data.progress
console.log(data)

Upvotes: 0

Related Questions