6

I want to replace part of the string with asterisk (* sign). How can I achieve that? Been searching around but I can't find a solution for it.

For example, I getting 0123456789 from backend, but I want to display it as ******6789 only.

Please advise. Many thanks.

1
  • 1
    keep in mind anyone will be able to see what you sent from the backend, modifying in the frontend will not hide it from the end user. Commented Jan 31, 2020 at 15:24

3 Answers 3

10

Try this:

void main(List<String> arguments) {
  String test = "0123456789";
  int numSpace = 6;
  String result = test.replaceRange(0, numSpace, '*' * numSpace);
  print("original: ${test}  replaced: ${result}");
}

Notice in dart the multiply operator can be used against string, which basically just creates N version of the string. So in the example, we are padding the string 6 times with'*'.

Output:

original: 0123456789  replaced: ******6789
Sign up to request clarification or add additional context in comments.

Comments

9

try using replaceRange. It works like magic, no need for regex. its replaces your range of values with a string of your choice.

//for example
prefixMomoNum = prefs.getString("0267268224");

prefixMomoNum = prefixMomoNum.replaceRange(3, 6, "****");
//Output 026****8224 

Comments

6

You can easily achieve it with a RegExp that matches all characters but the last n char.

Example:

void main() {
  String number = "123456789";
  String secure = number.replaceAll(RegExp(r'.(?=.{4})'),'*'); // here n=4
  print(secure);
}

Output: *****6789

Hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.