FabianoLothor
FabianoLothor

Reputation: 2985

Replace any character in a javascript string

I want convert this string:

string with characters like áéíóú

to

#################################

This "parágrafo".replace(/\wW*/g, "#") returns "###á#####"

Upvotes: 0

Views: 93

Answers (5)

melpomene
melpomene

Reputation: 85887

It looks like your regex lost a few characters somewhere (and gained a *). It should be /[\w\W]/ instead:

var str = "parágrafo".replace(/[\w\W]/g, "#");

console.log(str);

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

repeat() cannot be used in IE so I will suggest looping over to the str length to get string with value #.

let str = 'string with caracthers like áéíóú';
let result ='';
for(var i=0; i<str.length; i++){
  result += '#';
}
console.log(result);

Upvotes: 0

Barmar
Barmar

Reputation: 782498

The other answers using .repeat() are probably better ways to do this. This answer mainly serves to explain what's wrong with your code and how it could be done correctly.

\w doesn't match accented letters for some reason, that's why á ends up in the output. But even if this weren't a problem, it wouldn't match the spaces between words.

You can use ., which matches any character except newline.

console.log("string with caracthers like áéíóú`".replace(/./g, "#"));

If you also want to replace newlines with #, add the s modifier.

console.log(`string with caracthers like áéíóú
and also newlines`.replace(/./gs, "#"));

Oops, that's a very new feature in ES2018, not available in all browsers yet. You can use /.|\n.g for better portability.

console.log(`string with caracthers like áéíóú
and also newlines`.replace(/.|\n/g, "#"));

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138537

"#".repeat("string with characters".length)

No need for replace.

Upvotes: 0

Eddie
Eddie

Reputation: 26854

One option is using repeat()

let str = 'string with caracthers like áéíóú';

let result = "#".repeat(str.length);

console.log(result);

Doc: repeat()

Upvotes: 2

Related Questions