Determine if string is in base64 using JavaScript

前端 未结 10 1421
悲哀的现实
悲哀的现实 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条回答
  •  天涯浪人
    2020-12-28 15:21

    I would use a regular expression for that. Try this one:

    /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
    

    Explanation:

    ^                          # Start of input
    ([0-9a-zA-Z+/]{4})*        # Groups of 4 valid characters decode
                               # to 24 bits of data for each group
    (                          # Either ending with:
        ([0-9a-zA-Z+/]{2}==)   # two valid characters followed by ==
        |                      # , or
        ([0-9a-zA-Z+/]{3}=)    # three valid characters followed by =
    )?                         # , or nothing
    $                          # End of input
    

提交回复
热议问题