If Statements Failing in Loop Caused by Break?

I’m using a Javascript function to update a class whenever a value is changed, using “onchange” on an “Input” statement and I can’t for the life of me figure out why it skips my “if/elif” statements. I’ve been using “console.log” to verify the values/types immediately before the if statements and it just keeps shooting straight to the “else”.

The relevant code for the function is below. Where segmentTank = 2, loopTank = 2, segmentOrder = 3, and loopOrder = 2 I would have expected the first “if” statement to execute and give me an “If 1” in the console, but the console indicates it jumps straight to the “else”.

I’m wondering what silly mistake I’m making that I keep missing. Am I using “break” incorrectly?

function update_manualClass(segmentId){
        console.log('Updating manual class for segment:', segmentId);
        var segmentOrderInput = document.querySelector("input[name='Order_name_" + segmentId + "']");
        var segmentTankInput = document.querySelector("input[name='Tank_Number_name_" + segmentId + "']");
        if (!segmentOrderInput || !segmentTankInput) {
            console.error('Failed to find segment inputs for segment:', segmentId);
            console.log('Segment Order input:', segmentOrderInput);
            console.log('Segment Tank input:', segmentTankInput);
            return;
        }
        var segmentOrder = parseInt(segmentOrderInput.value);
        var segmentTank = parseInt(segmentTankInput.value);
        console.log('Segment order:', segmentOrder);
        console.log('Segment tank:', segmentTank);
        var table = document.querySelector("#table2");
        console.log("Table:", table);
        var previousSegmentOrder = [];
        for (var i = 0; i < table.rows.length - 1; i++) {
            //var row=table.rows[i+1];
            var loopOrderInput=table.rows[i+1].cells[0].querySelector("input[name^='Order_name_']");
            var loopTankInput=table.rows[i+1].cells[1].querySelector("input[name^='Tank_Number_name_']");
            console.log('Loop Order input:', loopOrderInput);
            console.log('Loop Tank input:', loopTankInput);
            var loopOrder = parseInt(loopOrderInput.value);
            var loopTank = parseInt(loopTankInput.value);
            console.log('Loop order:', loopOrder, typeof loopOrder);
            console.log('Loop tank:', loopTank, typeof loopTank);
            console.log('segmentTank:', segmentTank, typeof segmentTank);
            console.log('segmentOrder:', segmentOrder, typeof segmentOrder);
            if (segmentTank == loopTank && loopOrder < segmentOrder) {
                previousSegmentOrder = [];
                previousSegmentOrder.push(loopOrder);
                console.log('If 1:', previousSegmentOrder);
            }
            else if (segmentTank == loopTank && loopOrder == previousSegmentOrder[0] && previousSegmentOrder.length == 0){
                var fillPressureInput = document.getElementsByName("Fill_Pressure_name_" + segmentId)[0];
                var tankSizeInput = document.getElementsByName("Tank_Size_name_" + segmentId)[0];
                console.log('If 2', previousSegmentOrder);
                manualClass = "Manual"
                fillPressureInput.classList = manualClass;
                tankSizeInput.classList = manualClass;
                break;
            }
            else if (segmentTank == loopTank && loopOrder == previousSegmentOrder[0]){
                var fillPressureInput = document.getElementsByName("Fill_Pressure_name_" + segmentId)[0];
                var tankSizeInput = document.getElementsByName("Tank_Size_name_" + segmentId)[0];
                console.log('If 3', previousSegmentOrder);
                manualClass = ""
                fillPressureInput.classList = manualClass;
                tankSizeInput.classList = manualClass;
                break;
            }
            else {
                console.log('Did not work', previousSegmentOrder);
            }
        }
    }

How to export function inside of react functional component to be called in js file

I want to show a counter of how many comparisons my sorting algorithm is making (which is in a vanilla js file) by calling a function (or by simply changing the useState value directly) that is in my react file. I have been trying a few things but none are working, either I run into the problem of not being able to export a function that is in my react functional component or the counter will simply not show the update count (I would like for the count to be updated in real time. Anyone know a simple solution? I have found a potential solution but it seems to be too complicated for what seems to what could potentially have a simple solution

my vanilla js File:

export async function bubbleSort(arr){
    let swapped = false;
    for(var i = 0;i<arr.length-1;i++){
        swapped = false
        
        for(var j = 0;j<arr.length-1-i;j++){
            if(arr[j] > arr[j+1]){ 
                document.getElementById(j).style.backgroundColor = "green"
                document.getElementById(j+1).style.backgroundColor = "red"
                //**********************************
                //Add update counter Here
                //***********************************
                await delay(50);
                swap(j, j +1)
                let temp = arr[j]
                arr[j]=arr[j +1];
                arr[j +1] = temp;
                swapped = true
            }else{
                document.getElementById(j).style.backgroundColor = "green";
                document.getElementById(j +1).style.backgroundColor = "green"; 
                await delay(50)
            }
            
            document.getElementById(j).style.backgroundColor = "";
            document.getElementById(j +1).style.backgroundColor = "green";
            
        } 
        if(!swapped){
            for(let k = 0;k<=i;k++){
                document.getElementById(k).style.backgroundColor = "green";
                await delay(30)
            }
            break
        }
        if(j == 0 && i == arr.length-2)document.getElementById(j).style.backgroundColor = "green";
    }
}

my react file:

// export function callUpdateBubble(){
//   updateBubbleCount();
// }
function SortingPage(){
  const navigate = useNavigate();
  const [lines, setLines] = useState([]);

  //This counter ********************************
  const [bubbleCount, setBubbleCount] = useState(0)
  //*********************************************

//This function ********************************
  function updateBubbleCount(){
    setBubbleCount(bubbleCount+ 1)
  }
//*********************************************

  let idx = 0;
  useEffect(() => {
    resetArray()
  }, []);
  function resetArray(length) {
    const arr = [];
    let i
    for (i = 0; i < 30; i++) {
      arr.push(Math.floor(Math.random() * (350-5) + 5));
    }
    
    setLines(arr);
  }
  function getWidth(){
    let x = lines.length;
    if(x<10){
        return 30;
    }else if(x<30){
        return 20;
    }else if(x<40){
        return 10;
    }else if(x<60){
        return 5;
    }else{
        return 3;
    }
    
  }
  function deletes(){
    let length = lines.length-1;
    setLines(lines.filter(line => line !== lines[length]))
    
  }
  function bubble(){
    bubbleSort(lines)
  }
  
    return (
      <>
        <header className="header">
          <a className="logo" onClick={() => navigate("/")}>
            Algorithms Visualizer
          </a>
          <nav className="navbar">
            <a onClick={() => navigate("/sorting")}>Sorting Algorithms</a>
            <a onClick={() => navigate("/pathfinding")}>
              Pathfinding Algorithms
            </a>
          </nav>
        </header>
        <div className="container">
          {lines.length > 0 &&
            lines.map((line, idx) => (
              <div
                key={idx}
                id={idx++}
                className="line"
                style={{
                  height: `${line * 1.3 + 30}px`,
                  padding: `0px ${getWidth()}px`,
                  backgroundColor: ""
                }}
              ></div>
            ))}

          <button className="bubble" onClick={bubble}>
            Bubble Sort
          </button>
          <div className="count" style={{paddingLeft: "20px"}}>{bubbleCount}</div>
        </div>
      </>
    );
  

  
}

export default SortingPage;

I have tried exporting functions that will update the useState, I have also tried passing the useState variables as arguements.

Get token details max transaction details for ERC 20 tokens

I’ve been trying to figure out how some telegram scanners bots get the maximum buy and sell transaction and display it in eth along with determining tax of the token. Tax is probably a lot easier to figure out but I’m not sure how to go about buy and sell transaction limit

A lot of new pairs tend to start off with 1-2% buy and sell and i am working on a bot similar to sniper bots that performs these buys on new tokens. If my input will result to a higher buy % I obviously want to submit the transaction with a lower eth value.

Anyone have a better solution to my current though process because I imagine that would be really really slow.

My current thought process is basically start with the eth I want to use and if the transaction reverts, decrease it by a .0001 or something small, until I find a maximum eth value allowed.

ReactNativeBlobUtil Error: Download interrupted

Problem Description

RN Project Version: 0.72.1


ReactNativeBlobUtil (https://www.npmjs.com/package/react-native-blob-util) Version: ^0.18.3


I’ve created a function for my React Native application that downloads a webm audio file given a URL (passed URL returns audio/webm) and filename (passed filename always ends in .webm). While it sometimes completely downloads the audio file correctly to the downloads folder, other times it stops halfway and throws Error: Download interrupted. I’ve checked the URLs that lead to these errors and they’re still visible in the browser so I don’t understand why this error is happening. Examples of URLs which lead to these errors include:

I don’t know if these links are still going to be live when this question is seen as they have an expiration date. By the way, these links are generated by the react-native-ytdl library (https://www.npmjs.com/package/react-native-ytdl) version ^4.8.3 and I’m using an Android to test the app.

Function Definition:

const downloadFile = async (url: string, fileName: string) => {
        try {
            const storagePermissionGranted = await requestStoragePermission();
            if (storagePermissionGranted) {
                const dirs = RNFetchBlob.fs.dirs;
                const fileDir = Platform.OS === "android" ? dirs.DownloadDir : dirs.DocumentDir;
                const filePath = `${fileDir}/${fileName}`;
                
                const options = {
                    path: filePath
                };

                const task = ReactNativeBlobUtil.config( options ).fetch("GET", url, { "Cache-Control": "no-store", "Accept": "audio/webm" }); 
                task.then(result => {
                    console.log("Main file downloaded to: ", result.path());
                }).catch((error) => {
                    console.error(`Error while downloading main file ${fileName} with primary address ${url} and path ${filePath}:`, error);
                });
            }
        } catch (error) {
            console.error("Error while requesting storage permission:", error);
        }
};

I’ve also tried a function definition like below but it still leads to the same error.

const downloadFile = async (url: string, fileName: string, backupUrl: string) => {
        try {
            const storagePermissionGranted = await requestStoragePermission();
            if (storagePermissionGranted) {
                const dirs = RNFetchBlob.fs.dirs;
                const fileDir = Platform.OS === "android" ? dirs.DownloadDir : dirs.DocumentDir;
                ReactNativeBlobUtil
                    .config({
                        fileCache: true,
                        appendExt: "webm",
                    })
                    .fetch("GET", url, { "Cache-Control": "no-store" })
                    .then(async (cacheResult) => {
                        console.log(cacheResult);
                        let copyResult = await ReactNativeBlobUtil.MediaCollection.copyToMediaStore({
                        name: fileName,
                        parentFolder: "",
                        mimeType: "audio/webm"
                        }, "Audio", cacheResult.path());
                        console.log(copyResult);
                    })
                    .catch(error => {
                        console.error(`Error while downloading main file ${fileName} with primary address ${url} and path ${filePath}:`, error);
                //     })
            }
        } catch (error) {
            console.error("Error while requesting storage permission:", error);
        }
};

Solution for the initial JS process on a webpage that should be done each time the page is loaded

I have a huge DOM in my HTML file and a lot of elements that are manipulated by JavaScript each time the page is loaded.

These processes take time (not only the queries but also the manipulation processes) and it is not logical to do it every time.

The only way I figured out is to get the manipulated DOM created by JS from the browser DevTools and replace it with my original DOM. But I have to do it after each change on my file.

I would accept exporting the executed DOM after each change as the solution to this problem, but only if it could be done in a quick way.

What is the best practice in these situations?

How is this span element generated alongside each list item of this website HTML?

In http://guba.eastmoney.com/list,600007.html, there are tags beside some of the list items but these don’t show up when this site is loaded with JS disabled. I’m guessing they’re part of javascript scripts, main suspect being the list.js script since I can find keywords that show up in the element.

Here is the regular list item:

<tr class="listitem ">
   <td>
      <div class="read">88</div>
   </td>
   <td>
      <div class="reply">1</div>
   </td>
   <td>
      <div class="title"><span class="type_tag zx tag_1" title="资讯">资讯</span><a href="/news,600007,1328762009.html" title="中国国贸07月07日获沪股通增持8.35万股">中国国贸07月07日获沪股通增持8.35万股</a></div>
   </td>
   <td>
      <div class="author cl"><a class="nametext fl " href="/list,600007.html">中国国贸资讯</a><span class="jvbox fl"> </span></div>
   </td>
   <td>
      <div class="update mod_time">07-08 20:19</div>
   </td>
</tr>

Here is the list item with javascript disabled:

<tr class="listitem">
   <td>
      <div class="read">88</div>
   </td>
   <td>
      <div class="reply">1</div>
   </td>
   <td>
      <div class="title"><a href="/news,600007,1328762009.html">中国国贸07月07日获沪股通增持8.35万股</a></div>
   </td>
   <td>
      <div class="author"><a href="//i.eastmoney.com/4238113638898492">中国国贸资讯</a></div>
   </td>
   <td>
      <div class="update">07-08 08:15</div>
   </td>
</tr>

I’m looking at the network tab but I don’t see any requests that strike me as fetching for this info which makes me think its all done internally through the js scripts but I don’t know where its being done specifically. Are they just deducing these tags off logic or is there fetching being done from an outside source?

Javascript Variables Become Undefined After Making main.js into Module and Importing from Another .js File

I’m trying to have a variable be stated and exported from a .js file, imported to another .js file, and have this latter one be called as a module source to an HTML page. I’m having a console log the value of the variable in order to see if it’s a defined variable within the .html page. Whenever I do this, the console gives me an error saying that the variable is undefined. The following code is what I’m using. I’m using Visual Studio Code with the Live Server for JS.

export.js

export let MainNumber = 128;

main.js

import { MainNumber } from "./export.js";

index.html

<!DOCTYPE html>
<html lang="en">
    
    <head>
        <script type="module" src="main.js"></script>
    </head>

    <body>
        <script>
            console.log(MainNumber);
        </script>
    </body>
</html>

The error message:
Uncaught ReferenceError: MainNumber is not defined
http://127.0.0.1:5500/index.html:10

I expected the console to print 128. However, it seems to me that making main.js into a module is making MainNumber become undefined in index.html for some reason. If I state MainNumber directly into main.js, without importing it from another .js file, it prints just fine with no errors. For example, the code below works correctly.

main.js

let MainNumber=128;

index.html

<!DOCTYPE html>
<html lang="en">
    
    <head>
        <script src="main.js"></script>
    </head>

    <body>
        <script>
            console.log(MainNumber);
        </script>
    </body>
</html>

console prints:
128

How can I make my imported variables not be undefined in HTML? What is the reason for this last example of code to work just fine but the not the one before, that depends on importing it from elsewhere and thus requiring main.js to be defined as a module? Thanks in advance. I have looked into this a lot but I can’t make sense of it.

career advice/help (mobile/web developer) SOS [closed]

Hello guys hope you’re having a great day, I have studied both web and app development in these last 2 years where I went thru Html/CSS/PHP/Javascript/Bootstrap, Java/ Kotlin / Swift/Dart in mobile, and now I am lost what should be my next move (and of course, I haven’t dove any deep in anything it was one year for web dev and one year for app dev)

Tailwind and vue v-html

I have a vue component that takes a prop of raw html, the HTML comes from a wysiwyg which uses tailwind classes to do the styling just like our vue app.

However when doing v-html="responseFromAPI" in my component the rawHTML remains unstyled due to tailwind and how it renders I am guessing. Is there a way I can get the response from api into a component and rendered correctly?

Add onClick handler to MapView in React?

I’m using the ArcGIS API for JavaScript to display a map and I want to get the selected feature when someone clicks on the map. This is my MapComponent

export const MapComponent = () => {
    const elementRef = useRef(null);
    const [view, setView] = useState<MapView>();
    const [selected, setSelected] = useState<Feature>();


    const handleClick = useCallback((e: any) => {
        if (!view) return;
        view.hitTest(e)
            .then(res => {
                if (res.results.length > 0) {
                    const feature = res.results[0];
                    if (feature.type === 'graphic') {
                        setSelected(feature.graphic.attributes)
                    }
                }
            })
    }, [view]);

    useEffect(() => {
        if (!view) return;
        const handle = view.on('click', handleClick)
        return handle && handle.remove();
    }, [view]);

    useEffect(() => {
        const loadMap = async () => {
            const { init } = await import('./Map');
            const mapView = init(elementRef.current);
            setView(mapView);
        }
        loadMap()
        return () => view && view.destroy();
    }, []);

    return (
        <>
            <div
                ref={elementRef}
                style={{ height: '500px', width: '800px' }}
            >
            </div>
            <pre>{JSON.stringify(selected, null, 2)}</pre>
        </>
    )
}

I initializaed the map in a useEffect and save the map view with useState, I saw in the documentation you have to add your event handlers on another useEffect and I tried to do that, but the function handleClick doesn’t run when I click on the map

Restoring the connection to the socket after a page refresh on the client

What I want:
I use node js. At the moment my project doesn’t have any logic, but I need to understand how sockets work.
I have a task list on the client side where I enter the name of the task, the repetition time and the time after which the task will stop.
I need the logs to be displayed both on the client and on the server.
For example, if the user entered:
“Task 1” repeat every 2 minutes and finish in an hour

Then both on the server and on the client in the console of the browser is displayed:

| "Task 1" started at 11:00 AM   |
| Completed task "Task 1" at 11:02 AM   |
| Started task "Task 1" at 11:02 AM   |
| Completed task "Task 1" at 11:04 AM   |
| ...  |
| ...  |
| Completed Task 1 task after the time at 12:00 AM  |

What’s the problem:
I’ve done everything, but the problem remains that if you refresh the site page, the connection to the socket is broken and a new one is created. This causes the new “Task Started” and “Task Completed” messages to not show up in the browser console.

What I tried to do:
I found an official article on my problem. I seemed to have done everything as it needed to be done, but it didn’t help. Refreshing the page still establishes a new connection. No new messages are displayed in the console.

My code:
server.js

const server = http.createServer(app);
const io = socketIO(server, {
  connectionStateRecovery: {
    maxDisconnectionDuration: 2 * 60 * 1000,
    skipMiddlewares: true,
  }
});

io.on('connection', (socket) => {
  if (socket.recovered) {
    console.log('Соединение восстановлено:', socket.id);
    // Восстановление состояния сокета
    // Ваш код для обработки восстановленного состояния сокета
  } else {
    console.log('Новое подключение:', socket.id);
    // Ваш код для нового подключения
  }
  

  // Обработчик запуска задачи
  socket.on('startTask', (data) => {
    const { duration, stopAfter, nameTask, userId } = data;

    // Проверка, есть ли уже активная задача для данного пользователя
    if (userTasks[userId]) {
      socket.emit('taskError', { message: `У вас уже есть активная задача ${userTasks[userId]}` });
      console.log(`У вас уже есть активная задача`);
      console.log(userTasks);
      return;
    }
    // Проверка, есть ли уже задача с таким именем для данного пользователя
    if (userTasks[userId] && userTasks[userId][nameTask]) {
      socket.emit('taskError', { message: 'Не возможно запустить ещё одну задачу' });
      return;
    }
    

    const task = {
      id: taskId,
      duration,
      stopAfter,
      nameTask,
      userId,
      startTime: moment(),
      stopTime: moment().add(stopAfter, 'hours'),
    };

    // Добавление задачи в соответствующую структуру данных
    if (!userTasks[userId]) {
      userTasks[userId] = {};
    }
    userTasks[userId][nameTask] = task;
    taskId++;

    console.log(`Задача с id ${task.id} запущена ${new Date()}`);
    console.log(userTasks);
    // Отправка сообщения клиенту о запуске задачи
    socket.emit('taskStarted', task);

    // Запуск цикла задачи
    const taskInterval = setInterval(() => {
      const currentTime = moment();

      if (currentTime.isBefore(task.stopTime)) {
        console.log(`Задача с id ${task.id} завершена ${new Date()}`);
        socket.emit('taskStarted', task);

        console.log(`Задача с id ${task.id} запущена ${new Date()}`);
        socket.emit('taskCompleted', task);
      } else {
        console.log(`Задача с id ${task.id} завершена по истечению времени ${new Date()}`);
        clearInterval(taskInterval);
        delete userTasks[userId];
        socket.emit('taskFinished', task);
      }
    }, duration * 60000);

    // Обработчик остановки задачи
    socket.on('stopTask', (taskId) => {
      // Удаление задачи из соответствующей структуры данных
      if (userTasks[userId] && userTasks[userId][nameTask]) {
        console.log(`Задача с id ${taskId} завершена принудительно ${new Date()}`);
        clearInterval(taskInterval);
        delete userTasks[userId];
        socket.emit('taskForceStopped', taskId);
      }
    });
  });

  // Обработчик отключения клиента
  socket.on('disconnect', () => {
    console.log('Клиент отключился:', socket.id);
    // Получение userId из объекта socket
    const user = Object.keys(socket.rooms).find((room) => room !== socket.id);
    // Удаление информации о задачах пользователя при отключении
    if (userTasks[user]) {
      delete userTasks[user];
    }
  
    // Поиск и удаление соединения из хранилища по идентификатору пользователя
    const userId = Object.keys(userSockets).find((key) => userSockets[key] === socket);
    if (userId) {
      console.log(`Соединение ${socket.id} удалено из хранилища для пользователя ${userId}`);
    }
   
  });
  
});

index.html:

// Подключение к серверу WebSocket с сохраненным userId
    socket.on('connect', () => {
      console.log('Подключено к серверу WebSocket');
      if (socket.recovered) {
        console.log('Соединение восстановлено:', socket.id);
        // Восстановление состояния сокета
        // Ваш код для обработки восстановленного состояния сокета
      } else {
        console.log('Новое подключение:', socket.id);
        // Ваш код для нового подключения
      }

      console.log("recovered?", socket.recovered);
/*
      setTimeout(() => {
        if (socket.io.engine) {
          // close the low-level connection and trigger a reconnection
          socket.io.engine.close();
        }
      }, 10000);*/
    });

    // Попытка восстановить соединение при обновлении страницы
    if (socket.connected) {
      console.log('Connection already established');
    } else {
      console.log('Attempting to reconnect');
      socket.connect();
    }
    // Обработчик запуска задачи
    function startTask(taskId) {
      const duration = document.getElementById(`duration${taskId}`).value;
      const stopAfter = document.getElementById(`stopAfter${taskId}`).value;
      const nameTask = document.getElementById(`nameTask${taskId}`).value;
      //const userId = document.getElementById('userId').value;

      socket.emit('startTask', {
        duration,
        stopAfter,
        nameTask,
        userId
      });
    }

    // Обработчик остановки задачи
    function stopTask(taskId) {
      socket.emit('stopTask', taskId);
    }

    // Обработчик запуска задачи на сервере
    socket.on('taskStarted', (task) => {
      console.log(`Задача с id ${task.id} запущена ${new Date()}`);

    });

    // Обработчик завершения задачи на сервере
    socket.on('taskCompleted', (task) => {
      console.log(`Задача с id ${task.id} завершена ${new Date()}`);
    });

    // Обработчик завершения задачи по истечению времени на сервере
    socket.on('taskFinished', (task) => {
      console.log(`Задача с id ${task.id} завершена по истечению времени ${new Date()}`);
    });

    // Обработчик принудительной остановки задачи на сервере
    socket.on('taskForceStopped', (taskId) => {
      console.log(`Задача с id ${taskId} завершена принудительно ${new Date()}`);
    });

    // Обработчик ошибки запуска задачи на сервере
    socket.on('taskError', (error) => {
      console.log('Ошибка запуска задачи:', error.message, ' ${new Date()}');
    });

Please help me to reconnect with socket after refreshing page or other way to output new messages in the console of the browser. Sorry for my English. Full Code: https://drive.google.com/file/d/1-AyA8UPqRpALAkjH-A9wDkkIstD3v2n9/view?usp=drive_link

Identifier ‘element’ has already been declared [closed]

let isBoomerang = function(points) {
    const a =points[0];
    const b =points[1];
    const c =points[2];
    let k = [],
    
    k.push(a[1]/a[0]);
    k.push(b[1]/b[0]);
    k.push(c[1]/c[0]);
 
    k[0] == k[1] || k[0] == k[2] || k[1] == k[2] ? false : true;

};

It says Identifier ‘k’ has already been declared. I thought I have declared the array and then I can use the push method? I dont know why it said I am redeclaring the k…

Vue.js dynamic component registration leads to ‘Uknown custom element’ warning

I’m trying to register Vue components at runtime. The components are registered based on data items in a database (each item registers it’s own individual component).

template: parentTemplate,
...
methods: {
    createdComponent() {
        ...
        repo.search(criteria).then((results) => {
            results.forEach((element) => {
                Vue.component('component-prefix-' + element.name, {
                    template: childTemplate,
                });
            }
        });
    }
}
...

In the parentTemplate I then use:

...
<component :is="dynamicComponentName" />
...

But Vue won’t see the child component as a registered component and gives me [Vue warn]: Unknown custom element: <name-of-the-dynamic-component>.

Any ideas? Thanks!

How to replace a repeated string between delimiters?

I need to replace a sequence of text inside a delimiter, exactly the number of times it occurs. E.g. I have a text like this:

"Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH too but it doesn't moo; bah!"

I want to replace each “moo;” between “&” and “RGH” with an “A”, so I expect that:

"Cow says &ARGH but also &AAARGH and &AAAAARGH but it doesn't moo; bah!"

In other words, I have to replace each “moo;” between “&” and “RGH” with an “A”. I have to replace it via javascript on the whole text using a single regexp (if possible)
I did a lot of attempts, e.g.:

var a="Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH but it doesn't moo; bah!"
a=a.replace(/(?<=&)((moo;)1?)+RGH/g,"A");
// a=a.replace(/&(moo;)+RGH/g,"A")
// a=a.replace(/&(?=moo;)1RGH/g,"A"
console.log(a);

but without evident success.
The idea is that each “moo;” must be replaced with “A” only if present along with other “moo;”s between a “&” and “RGH”

Any suggestion? Thanks!