Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position.

My current approach involves converting the Uint8Array into a string and then searching for the desired string within that newly created string.

Here's a snippet of my code:

    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);

The issue I'm facing is that utf-8 characters are encoded in variable-length bytes (ranging from 1 to 4 bytes). As a result, the length of the string I obtain is shorter than the actual length of the UInt8Array. This discrepancy causes the index derived from the string search to not align with where the '/ByteRange' string exists in the UInt8Array, leading to incorrect insertion placement.

Is there a method to obtain a 1-byte string representation of the UInt8Array, similar to ASCII?

Answer №1

My solution involved making a modification:

I updated <const pdfStr = new TextDecoder('utf-8').decode(array);>
to

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying unique input values with ng-model

Within the controller, there is a variable that monitors the page index (starting at 0) for a paginated table: var page { pageNumber: 0; } Query: How can I display this pageNumber variable in the HTML, but always incremented by +1? (since the index=0 p ...

The angular controller function is failing to set $scope.value

I've been facing an issue with setting an Angular variable value in a controller function that is created by a directive. For some reason, it doesn't seem to work when I try to assign the value within the controller function, even though it displ ...

Enhancing the session helper in Silex with additional values

Hey there, I'm currently working on a basic shopping cart using an MVC framework called Silex. However, I've run into a JavaScript/AJAX issue that I could use some help with. My problem arises when trying to add a product to the basket. The issue ...

Issues with navigating sliders

I've encountered a problem with my slider arrows while following a YouTube tutorial. They are supposed to appear next to the picture and testimonial, but instead, they are showing up at the top. This issue wasn't present initially, but after enco ...

Dividing a string in JavaScript to generate fresh arrays

I am currently dealing with the following string: "ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0 ...

Ways to fix the TypeError that occurs when attempting to convert undefined or null to an object by using Function.keys

I am attempting to conceal the field. When the user clicks on glyphicon-eye-open, I will display glyphicon-eye-close and set the condition to true. If the condition is true, then I push that value into an array. Here is the function I am using, I have two ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

Sometimes, it feels like TypeScript's async await does not actually wait for the task to complete before moving on

Recently, I have been transitioning to using the async await pattern more frequently instead of the traditional Promise syntax because it can help in keeping the code structure cleaner. After some experimentation, I felt like I had a good grasp on how to u ...

Node.js - CSRF Protection Token Undefined

I've been facing challenges with setting up CSRF token generation, and I seem to be missing something. server.js: // configuration ====================================================================== var express = require('express'); va ...

Using AngularJS to pass radio button value to a $http.post request

Can you please advise on how to extract the value from a radio button and send it using $http.post in AngularJS? Here is an example: HTML <input name="group1" type="radio" id="test1" value="4"/> <label for="test1">Four paintings</label ...

Issue: TypeError - The function addTicket is not recognized as a valid function. Utilize the useState hook within the modal component

I'm currently facing some challenges with the implementation of the useState hook and I am struggling to understand why it is not working as expected. My project involves creating a basic ticket system where users can click on a button to open a moda ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

What's the CSS equivalent of Java's window.pack() method?

I'm relatively new to css and I'm attempting to create a border around a <div>. My goal is for the border to be limited to the size of the elements inside the div and adjust dynamically in proportion to any new objects that may appear or di ...

Tips for ensuring the drop down button remains selected

My goal is to keep the sorting drop-down button selected after clicking on it, instead of resetting back to "All". Below are my HTML, CSS, and jQuery code. You can view the functionality on my website here: jQuery/Javascript: $(document).ready(function($ ...

A step-by-step guide on displaying a loading spinner during the retrieval and assembly of a component framework (Astro Island) with Vue and AstroJS

Here is the astro code I'm working on: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title= ...

Using dynamic tag names within React JSX can greatly enhance the flexibility and

I'm working on creating a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is determined by a prop. Here is how I attempted to approach it: <h{this.props.level}>Hello</h{this.props.level}> My expected out ...

Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api. The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information. I ...

Maintaining the $index value across all pagination pages in AngularJS while matching it with the items in the data list

Is there a way to maintain the original $index numbers in my list data after pagination? For example, if data.length is 50 and they start from index 0, the first page contains 10 items ending at index 9. The next item on the second page should start at in ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...