How to delete special characters and a specific word from a json/string?

Viewed 523

I am trying to remove a specific word from a JSON file.

I have this to remove special characters like : , {} []

  JSON.stringify(csv, null, 2).replace(
    /[!@#$^&%*()+=[\]/{}|:<>?,.\\-]/g,
    '',
  ),

but then there is the word "data", how can I add that word to be removed from the string in that regex above?

And also I would like to remove the "" around the strings. Like "hola" I want it to be only hola

3 Answers

You may add the x|y pattern:

/"data":|[!"@#$^&%*()+=[\]/{}|:<>?,.\\-]/g

var csv = {
    "data":[
        { "animal":"dog", "name":"Fido" },
        { "animal":"cat", "name":"Felix" },
        { "animal":"hamster", "name":"Lightning" }
    ]
}
var x = JSON.stringify(csv, null, 2).replace(/"data":|[!"@#$^&%*()+=[\]/{}|:<>?,.\\-]/g, '');

console.log(x);

Try this

var result = str.replace(/\bdata\b|["!@#$^&%*()+=[\]/{}|:<>?,.\\-]/g, '')

I would make the regex in kind of the opposite way. This regex is the word data, or not the characters within [^]

/(data|[^a-zA-Z0-9,.; ])/g
Related