Determine if string is in base64 using JavaScript

前端 未结 10 1424
悲哀的现实
悲哀的现实 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 14:59

    This should do the trick.

    function isBase64(str) {
        if (str ==='' || str.trim() ===''){ return false; }
        try {
            return btoa(atob(str)) == str;
        } catch (err) {
            return false;
        }
    }
    

提交回复
热议问题