在 Uint8Array 中查找字符串的索引

find index of string in Uint8Array

我有一个 Uint8Array,它实际上是 PDF 文件的内容。我想找到位于该数组中的特定字符串的索引,以便我可以在该位置插入一些内容。

为此,我实际上是将 Uint8Array 转换为字符串,然后在该字符串中搜索我想要为其查找索引的字符串。

这是片段

    const pdfStr = new TextDecoder('utf-8').decode(array);
    
    // find ByteRange
            const byteRangePos = this.getSubstringIndex(pdfStr, '/ByteRange [', 1);
            if (byteRangePos === -1) {
                throw new Error(
                    'Failed to locate ByteRange.'
                );
            }
    
           getSubstringIndex = (str, substring, n) => {
            let times = 0, index = null;
    
            while (times < n && index !== -1) {
                index = str.indexOf(substring, index + 1);
                times++;
            }
    
            return index;
        }

array = this.updateArray(array, (byteRangePos + '/ByteRange '.length), byteRange);

我遇到的问题是 utf-8 字符以可变长度(1-4 字节)的字节编码,所以我得到的字符串的长度小于 UInt8Array 本身的长度,所以我通过搜索字符串得到的索引与 '/ByteRange' 字符串在 UInt8Array 中的实际位置不匹配,所以它在它应该插入之前被插入。

有什么方法可以得到 UInt8Array 的 1 字节字符串表示形式,如 ASCII 或类似的东西?

我通过更改

解决了问题

const pdfStr = new TextDecoder('utf-8').decode(array);

const pdfStr = new TextDecoder('ascii').decode(array);