Home > Blockchain >  Replace all occurrences of a string from a text file for a list of names
Replace all occurrences of a string from a text file for a list of names

Time:09-12

I have some typescript code that reads 5 players from a text file. The problem is I am unable to remove the word "player - " from all of them?

Example of the text file:

player - toby
player - coby
player - roby
player - poby
player - boby

Here is the code I wrote:

  const players = fs
    .readFileSync(`${__dirname}/db/players.txt`, {
      encoding: 'utf8',
      flag: 'r',
    })
    .toString().replace('player - ',"")
    .split('\n');

but it only is replacing for one person?

CodePudding user response:

You can try with regex to do it

.readFileSync(`${__dirname}/db/players.txt`, {
  encoding: 'utf8',
  flag: 'r',
})
.toString().replace(/player - /g,"")
.split('\n');

TS Oline Demo

CodePudding user response:

You can use split method. Your item will be two items of array. You need to get second part.

const data = ["player - toby", "player - coby","player - roby","player - poby","player - boby"]
  
const newData = data.map(item=> item.split(" - ")[1])
console.log(newData)
  • Related