Dart: Replace every letter in a string with an asterix using regxp

Viewed 5334

I was trying to replace every letter in a string with an asterix using Dart and am having some difficulty. In Javascript it is:

'test'.replace(/./g, '*');

So in Dart, I tried the following:

'test'.replaceAll(new RegExp(r'/.'), '*');
'test'.replaceAll(new RegExp(r'\/.'), '*');
'test'.replaceAll(new RegExp(r'/./'), '*');
'test'.replaceAll(new RegExp(r'\/.\/'), '*');

I obviously don't quite understand how this should work as cannot seem to make this work.

Can anyone advise the correct way to do this with a short explanation?

Thanks.

2 Answers
var regex = new RegExp(r'[a-zA-Z]')

var replaced = 'some string / with $ other = chars'.replaceAll(regex, '*');

DartPad example

To anyone who needs to remove Special characters and other letters in a given string. Use the format below.

  String str = "a12.334tyz.78x";
  
  var newStr = str.replaceAll(new RegExp(r'[a-zA-Z.]'), ''); 
  print(newStr);
  

result 1233478

Dart Pad https://dartpad.dev/

Related