pheromix
pheromix

Reputation: 19327

Regex does not work for replacing blank character

I want to replace all blank characters :

var immatriculation = " 31595 WWT  ";
var fs = require('fs');
    fs.writeFile('test_george.txt', immatriculation.replace(/ /g, ""), function (err) {
        if (err) throw err;
    });

At runtime I get " 31595WWT "; as you can see there are still the blank characters at the beginning and at the end.

So what is wrong ?

Upvotes: 0

Views: 24

Answers (3)

Reyno
Reyno

Reputation: 6505

Your regex seems fine, you could also try to use /\s/g. \s means "any whitespace character"

var immatriculation = " 31595 WWT  ";

var result = immatriculation.replace(/\s/g, "");

console.log(result);

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10194

Use String.replaceAll method.

var input = " 31595 WWT  ";
console.log(input.replaceAll(" ", ""));

Upvotes: 0

Tasos
Tasos

Reputation: 2036

This seems to work as expected:

const str = '   Hello World   ';
console.log(str.replace(/ /g,''));

Upvotes: 0

Related Questions