1
var string = '12345';

I want to replace 2 and 4 with 0, so I tried:

var output = string.replaceAll('2, 4', '0') // doesn't work

I am not sure if I need to use RegExp for this small stuff? Is there any other way to solve this?

2 Answers 2

2

You can achieve this with RegExp:

final output = string.replaceAll(RegExp(r"[24]"),'0');

[24] matches any character that is either 2 or 4.

Sign up to request clarification or add additional context in comments.

4 Comments

What if I want to use string interpolation in it, how will that work? For instance: I want to replace a variable RegExp(r"[$variable 4]", '0')
I am unaccepting this answer because I am not able to use string interpolation part in it.
This can easily be fixed, just use RegExp("[${variable}4]", '0'). I mean the r is just denoting a raw string here. You are quite new to this site, so maybe check the rules here. Changing the question is highly discouraged, as this makes the answers and efforts potentially useless or inappropriate. Better to ask a new question.
You're right, I shouldn't have upvoted and accepted your answer in the first place, I was very kind to you but thanks for teaching me a lesson :)
1

This works

void main() {
   var string = '12345';
    string = string.replaceAll('2', "0");
    string = string.replaceAll('4', "0");
    print(string);
}

1 Comment

Thanks but this isn't what I am looking for, I could also have done it 2 times.

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.