Leveraging javascript for substituting on-page javascript functionality

Dear fellow coders, I am still learning the ropes of Javascript, so please bear with me.

I’ve encountered this snippet on a webpage:

<script type="text/javascript"> bb1 = "oldcode"; bb2 = "morecodehgere"; bb3 = 160000;</script>

My goal is to substitute 1% of all page loads from oldcode to newcode.

There are numerous occurrences of this code on the same page that need replacing.

window.onload = replaceScript;
function replaceScript() {
var randomNumber = Math.floor(Math.random()*101);
var toReplace = 'oldcode';
var replaceWith ='newcode';
if (randomNumber === 1) {
document.body.innerHTML = document.body.innerHTML.replace(/toReplace/g, replaceWith);
 }
}

This is the current script I have implemented, but it’s not functioning as intended.

Is Javascript the best approach for achieving this task? If so, what would be the most efficient method?

Answer №1

When using the regular expression literal:

/toReplace/g

it generates a regular expression object that matches the specific string "toReplace". To create a regular expression that matches the actual value of the variable toReplace, you should utilize the RegExp constructor:

var re = new RegExp(toReplace, 'g');

Simply replacing the innerHTML of the body with an exact copy of itself is not recommended. The innerHTML property may not capture all aspects of the DOM and can overlook elements like dynamically added event listeners. Furthermore, it may behave differently across various browsers.

Applying a regular expression to replace portions of innerHTML is likely to yield unpredictable outcomes. While it might work satisfactorily on simple pages, it cannot be relied upon for complex webpages.

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

Rebuilding JSON data with stringify manipulation

I have a database with various cells and values stored under each cell. The cells in the database are: id, name, duration, date, and relationid. This is the code I am currently using: var result = {} properties.data.forEach(addToResult); //Retrieves ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Is it possible to update the event parameters with every click?

Is there a way to dynamically add a Select box for selecting a condition each time the "add" button is clicked? For example, when the add button is clicked, I would like the following elements to be continuously added: https://i.stack.imgur.com/6bad2.png ...

whether you need a cache factory or a regular object

As I embark on creating a mid-sized Angular application, one of my requirements is to store data and utilize it at the end of the user journey for sending to the server (as per company security policy regarding customer data transport). As a relatively new ...

Ways to address the issue with the Promise object showing as <pending>

I recently started using next JS and I'm facing an issue where my data is not getting displayed on a specific route. Can someone please help me understand why this is happening? Feel free to ask if you have any questions about my query. https://i.sst ...

Exploring various components within Material UI to effectively navigate between them

How can I use Material UI to navigate to a different component? Below is the code for my drawer list: <List> {['POS', 'Stock', 'Send email', 'Drafts'].map((text, index) => ( <List ...

Is there a way to showcase the contents of the angular "tags" object seamlessly?

Is there a way to show the content of the "tags" object using angular? I attempted to achieve it using {{gallery.tags.tag}} but unfortunately, it did not work import {IPhoto} from "./iphoto"; export interface IGallery { galleryId: string; title: ...

Eliminate the JSON object within jqGrid's posted data

The web page I'm working on features Filters with two buttons that load data for jqGrid when clicked. Clicking 'Filter' generates a postData json object and sends it to the server, which is working perfectly. However, I'm facing an is ...

Troubleshooting undefined values returned by getStaticProps in Next.js

I've been working on a Next.js blog and I'm trying to fetch all the blog posts from a directory during the build process. However, no matter what I try with getStaticProps, it always returns undefined in the main component. I've tested it in ...

The Date object and ISO date object yield varying results in their date displays

I am faced with the task of extracting a date value, converting it to an ISODate, and then searching a mongoDB collection that contains an object with a date value. The query is designed to compare the date of an event and determine if it falls on a weeken ...

Automate Spreadsheet Updates with Google Apps Script

I'm currently facing an issue while trying to paste csv data into a Google Sheet using the code provided below. Strangely, when I execute myFunction(), the data quickly appears in the Google Sheet but then vanishes instantly, almost as if sheet.clear( ...

Dealing with an XMLHttpRequest using app.post in node.js with express (JavaScript)

In my current project, I am working on implementing a filter functionality using checkboxes. The concept involves creating HTML for the checkbox that triggers a script to send DOM data to the server. Here is an example of the HTML code: <div class=&quo ...

Displaying the selected date from a date picker in both a label and a text box

$("#datepicker").datepicker(); I have implemented the datepicker function in my project and the input field associated with it looks like this: <input type="text" id="datepicker" name="fulldate" class="form-control wid-100"> <span id="#dpicker_ ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

Utilizing AngularJS for Managing JSON Data

I'm facing a new challenge and need some assistance. My goal is to create 9 buttons and a panel that will display movie details based on the button clicked. For example, if I click 'Transformers', I want the panel to show details about Trans ...

Leveraging Discord.JS to seamlessly transport users in Discord to their designated voice channel by assigning roles

I'm attempting to transfer all users with a specific role from a voice channel using a command like: !summon @role This command should bring only the users with that specific role to the voice channel where the command was entered My current code is ...

Error Encountered: Unable to Locate 'bootstrap' label in Bootstrap 5 Popover

I have been working on implementing a popover in my Angular 12 project using Bootstrap version v5.0.1. However, I am encountering a name error that I can't seem to resolve: var exampleEl = document.getElementById(item.name + index); var tooltip = ne ...

Retrieving object keys in Node.js based on their values

Wanting to create a function in nodejs 8.10 that returns a different object based on parameters provided, is there an easy way to include or exclude a key based on its value? For instance: // The current solution which can be improved // `c` might be und ...

Problem encountered with sending automated responses in Discord bot for updates on current events

Issue with Automated Replies in Discord.js' Functionality I'm currently developing a Discord bot using the Discord.js library in Node.js, and I've encountered a problem with the automatic replies feature. The bot's main task is to retr ...

How to incorporate a JavaScript class into a VueJS project

Looking to incorporate a JavaScript class into my Vue application. The class structure is as follows: class className { constructor() { ... } function1() { ... } static funtion2() { ... } } Attemptin ...