如何在node.js中将quoted-printable内容解码为普通字符串?

7
例如,我有一个字符串 "this=20is=20a=20string",我想将其转换为 "this is a string"。

尝试使用 mimelib https://github.com/andris9/mimelib - vinayr
mimelib是一个好的选择。 =20只是一个例子,它可以是任何东西,例如=27、=21——换句话说,是可打印的引用格式。 - dan gibson
mimelib不再维护,有没有其他替代建议? - roman
4个回答

9

使用 mimelib:

var mimelib = require("mimelib");
mimelib.decodeQuotedPrintable("this=20is=20a=20string") === "this is a string"
mimelib.decodeMimeWord("=?iso-8859-1?Q?=27text=27?=") === "'text'"

将以下关于编程的内容从英语翻译成中文。仅返回翻译后的文本:在引用可打印时编辑第二行以使其正确工作 - snies
mimelib 现在已经不再维护。 - sebix

1

可以使用quoted-printable package进行引用可打印编码和解码。

> var utf8 = require('utf8')
undefined
> var quotedPrintable = require('quoted-printable');
undefined
> var s = 'this=20is=20a=20string'
undefined
> utf8.decode(quotedPrintable.decode(s))
'this is a string'
> quotedPrintable.encode(utf8.encode('this is a string'))
'this is a string'

1

function decodeQuotedPrintable(data)
{
    // normalise end-of-line signals 
    data = data.replace(/(\r\n|\n|\r)/g, "\n");
        
    // replace equals sign at end-of-line with nothing
    data = data.replace(/=\n/g, "");

    // encoded text might contain percent signs
    // decode each section separately
    let bits = data.split("%");
    for (let i = 0; i < bits.length; i ++)
    {
        // replace equals sign with percent sign
        bits[i] = bits[i].replace(/=/g, "%");
        
        // decode the section
        bits[i] = decodeURIComponent(bits[i]);
    }
        
    // join the sections back together
    return(bits.join("%"));
}


1

这里有一个变量,您可以指定字符集:

function decodeQuotedPrintable(raw, charset='utf-8') {
    const dc = new TextDecoder(charset);
    return raw.replace(/[\t\x20]$/gm, "").replace(/=(?:\r\n?|\n)/g, "").replace(/((?:=[a-fA-F0-9]{2})+)/g, (m) => {
        const cd = m.substring(1).split('='), uArr=new Uint8Array(cd.length);
        for (let i = 0; i < cd.length; i++) {
            uArr[i] = parseInt(cd[i], 16);
        }
        return dc.decode(uArr);
    });
}

console.log(decodeQuotedPrintable('Freundliche Gr=C3=BCsse'));              // "Freundliche Grüsse"
console.log(decodeQuotedPrintable('I love =F0=9F=8D=95'));                  // "I love "
console.log(decodeQuotedPrintable('Freundliche Gr=FCsse', 'ISO-8859-1'));   // "Freundliche Grüsse"
console.log(decodeQuotedPrintable('Freundliche Gr=9Fsse', 'macintosh'));    // "Freundliche Grüsse"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接