2

I have string came from back end that in which I need to replace some value

I do this like this usr_.avatar_base64.Replace("data:image/jpeg;base64,", "")

But sometimes it has data:image/jpg;base64, so Can make some kind of OR in Replace to handle different variants?

4 Answers 4

5

Just chain another replace:

usr_.avatar_base64.Replace("data:image/jpeg;base64,", "")
                  .Replace("data:image/jpg;base64,", "")
6
  • Hm, but if first replace will do the trick, second will not works? Dec 7, 2018 at 19:24
  • @EugeneSukh what do you mean?
    – Ousmane D.
    Dec 7, 2018 at 19:25
  • If row contains data:image/jpeg;base64 first replace will replace this stuff, but second will not works, yes? Dec 7, 2018 at 19:26
  • @EugeneSukh If the first call to Replace() does not find a match, then the second call will and vice versa. Replace() doesn't throw an exception if no matches are found, so it's perfectly find to chain them in this manner. Dec 7, 2018 at 19:31
  • @EugeneSukh, the second doing nothing in that situation is not the same as it not working. Dec 7, 2018 at 19:32
1
var output = base64.Contains("data:image/jpeg;base64") ? 
base64.Replace("data:image/jpeg;base64,", "") : 
base64.Replace("data:image/jpg;base64,", "") ;  
1
  • In practice yea :P
    – Tezzy
    Dec 7, 2018 at 19:25
0

This is the perfect scenario for RegEx.

Regex.Replace(usr_.avatar_base64, "data:image/jpe?g;base64", "");

The ? denotes an optional character, so this will match jpeg and jpg.

See the Microsoft documentation here.

1
  • 2
    This is definitely not the PERFECT scenario for RegEx.
    – Jay
    Dec 7, 2018 at 19:29
0

The data can be in other formats too, so just get everything after the comma :

string base64 = usr_.avatar_base64.Split(',').Last();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.