Wcan Wcan - 5 months ago 10
Node.js Question

Strip special characters except underscore and generate exact output as input in javascript

I'm trying to strip special characters from the object list, also generate same output format as input.

obj= {"col1": "es_officer_id", "col2": "es_officer_name", "col3": "es_officer_fname"};

var test = [];

for (var prop in obj)
{
test.push(obj[prop].replace(/[^_ a-zA-Z 0-9]+/g, ''));
}

return test;


Problem No 1:

it gives me this error where as if i try this same .replace with string it works absolutely fine

TypeError: obj[prop].replace is not a function


Problem No 2:

I've tried to output the objects in the following format but it didn't work.
it gives me the prop as it it instead of col1, col2, col3

test.push({prop: obj[prop]});

Answer

Are you sure that others libraries or code is not doing all your objects dirty, try this:

for (var prop in obj) {
  if( obj.hasOwnProperty( prop ) ) {
     test.push(obj[prop].replace(/[^_ a-zA-Z 0-9]+/g, ''));
  } 
}

The second problem you can create a new hash:

var test = {}
for (var prop in obj) {
  if( obj.hasOwnProperty( prop ) ) {
     test[prop]=obj[prop].replace(/[^_ a-zA-Z 0-9]+/g, '');
  } 
}