Reacting
Reacting

Reputation: 6123

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

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

Upvotes: 2

Views: 1195

Answers (3)

aseferov
aseferov

Reputation: 6393

Try this

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

Upvotes: 2

gaetanoM
gaetanoM

Reputation: 42044

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);

Upvotes: 2

Nick Ellis
Nick Ellis

Reputation: 1077

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

Upvotes: 0

Related Questions