learnNcode
learnNcode

Reputation: 149

How can i replace all special characters in a string in nodejs using replace?

experience(years)d.o.b (dd/mm/yyyy) -- how can I remove (),.,/, spaces from the string using single replace function in node. I would like to get like

experienceyearsdobddmmyyyy

//pgm converts xl to json

const exceltojson = require('xlsx-to-json');
const fs = require('fs');
exceltojson({
    input: "xl.xlsx",
    output: 'xl.txt',// Don't need output
    sheet: 'student_Details'
  },
  function(err, result) {
    if (err) {
      console.error(err);
      return;
    }
    else{
      console.log(result+'   result')
      console.log(result)
    }
    const newResult = result.map(obj => {
      const newObj = Object.keys(obj).reduce((acc, key) => {
        const newKey = key.replace(/ /g, '').toLowerCase();
        acc[newKey] = obj[key];
        console.log(newKey+'   newKey ')
        return acc;
      }, {});
      return newObj;
    });
    fs.writeFileSync('xl.json', JSON.stringify(newResult));
  }
)

Upvotes: 1

Views: 2007

Answers (2)

Mark Paine
Mark Paine

Reputation: 1894

> re = /[\(\)\/\.\ ]+/g
/[\(\)\/\.\ ]+/g
> s="(10/04/2020)"
'(10/04/2020)'
> s.replace(re, "")
'10042020'

Upvotes: 3

anees
anees

Reputation: 1855

you can use regex to replace all those chracters.

let str = "experience(years)d.o.b (dd/mm/yyyy)";

function stripedStr(s){
  return s.replace(/[\(,\),\.,\/,\-,\_, ,]/g, "");
}

console.log(stripedStr(str));

Upvotes: 2

Related Questions