Determine if string is in base64 using JavaScript

前端 未结 10 1422
悲哀的现实
悲哀的现实 2020-12-28 14:38

I\'m using the window.atob(\'string\') function to decode a string from base64 to a string. Now I wonder, is there any way to check that \'string\' is actually

10条回答
  •  -上瘾入骨i
    2020-12-28 15:05

    As there are mostly two possibilities posted here (regex vs try catch) I did compare the performance of both: https://jsperf.com/base64-check/

    Regex solution seems to be much faster and clear winner. Not sure if the regex catches all cases but for my tests it worked perfectly.

    Thanks to @Philzen for the regex!

    p.s.

    In case someone is interested in finding the fastest way to safely decode a base64 string (that's how I came here): https://jsperf.com/base64-decoding-check

提交回复
热议问题