NodeJS 检查是否使用Base64编码

xxhby3vn  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(173)

我想检查一个字符串是否是Base64编码的。
以下是我的尝试:

var base64Rejex = new RegExp(
    /([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==$)/
)

var base64Data = 'RULES'
var isBase64Valid = base64Rejex.test(base64Data) // base64Data is the base64 string

if (isBase64Valid) {
    // True if in Base64 format
    console.log('It is base64')
    var data = new Buffer(base64Data, 'base64').toString('ascii')
    console.log('THIS IS IS ' + data)
} else {
    // False if not in Base64 format
    console.log('it is not in base64')
}

即使上面的字符串是 * 不是 * Base64编码的,我的代码总是输出它是。
如何检查字符串是否是Base64编码的?我需要在正则表达式中修改什么吗?

bwntbbo3

bwntbbo31#

尝试下面的代码,其中str是要检查的字符串。

Buffer.from(str, 'base64').toString('base64') === str

相关问题