Replacing strings with special characters appears to be malfunctioning

After spending countless hours searching through Stack Overflow and other resources, I am still unable to understand what is happening here. Any assistance would be greatly appreciated!

I am trying to convert document.write('</div>'); to -> < /div>

I have simplified the problem to its most basic form in the following HTML example.

<script>
var str = "document.write('</div>');";
str = str.replace("/document.write/g","");
console.log(str); //</div>
</script>

Answer №1

By removing the quotes, the code will function properly. The presence of quotes causes it to be read as a string literal, whereas regular expressions are enclosed in plain /s.

Additionally, the . character must be escaped to ensure it only matches a period and not any other single character.

<script>
var str = "document.write('</div>');";
str = str.replace(/document\.write/g,"");
console.log(str); //</div>
</script>

Answer №2

The String method replace() has the flexibility to work with either a string or a regular expression. When using a string, the syntax looks like this:

var str = "Hello, World!";
str = str.replace("Hello", "");
console.log(str);

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

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

Ensure that the v-for attribute has an increased value

Is there a way to have an incremented value in this code snippet? :data-value="Math.round(elecs[index].obtenus/elecs[index].maxsiege*100) Here is my attempt at iteration : :data-value="Math.round(result += elecs[index].obtenus/elecs[index].maxsiege*100 ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format: public sids: Map<SocketId, Set<Room>> = new Map(); When I try to access it using the code below: io.of("/").adapter.sids.forEach(function(va ...

Guide on loading a div with a flash object without showing it on the screen (element is loaded but remains hidden)

Is there a way to achieve an effect that is somewhere between using display: none and visibility: hidden? Specifically, I am trying to have a div element (containing flash content) loaded but not displayed on the page. Just for clarification: I have embed ...

Upon initial page load, React JS is unable to fetch the data but it functions correctly when triggered by a click

Here is the code I am working with: var CommonHeader = require('./header/CommonHeader.jsx'); var ListOptions = require('./header/ListOptions.jsx'); var SortableTable = require('../shared/SortableTable.jsx'); var ColumnDefinit ...

Troubleshooting the issue of AngularJs location.path not successfully transferring parameters

My page has a Login section. Login.html <ion-view view-title="Login" name="login-view"> <ion-content class="padding"> <div class="list list-inset"> <label class="item item-input"> <input type="te ...

What is the reason for initializing I with the length of the response?

I am attempting to generate a table using an AJAX JSON response, but the for loop sets i to the maximum value right away. $.ajax(settings).done(function (response) { console.log(response); var i = ""; td = document.createElement('td'); t ...

What is the method for retrieving URL parameters in react-router-dom 4 when utilizing the Route render prop rather than the Route component prop?

I am currently utilizing react-router-dom v 4.0.0. Within my top-level <App /> component where my react router is rendered, I have three routes. The first two routes function correctly, however, the third route does not. render() { const pageMa ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Dealing with Unicode Issues in JSON Encoding and MySQL

Here is some JavaScript code that I have: The code works fine (the makewindows function has been changed to show it as a PHP variable), but there seems to be an issue with Unicode characters in the HTML. Only characters before the first Unicode character ...

Why does the Mongoose query findOne({params}) return null when it successfully runs in the mongo shell?

Here are the software versions currently being used: mongoose 4.10.8, mongodb 3.4, express 4.13.4, nodejs 6.11.1, npm 3.10.10, When querying in the Mongo shell, I can easily find a user using findOne: > db.users.findOne({"admin":"true"}).pretty() & ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

Comparing Jscript's impact on CSS classes to the power of Json

On my HTML page, there is a div that looks like this: <div class="circle active" id="prg_inizio"> bla bla bla </div> After making an Ajax call, I receive a JSON result and need to update the class name from "circle active" to "circle done." ...

Eliminate a specific parameter from a URL query

Is there a way to effectively remove a specific variable from a query string? For example, if we have a query string like: $query_string = "first=val1&amp;second=val2&amp;third=val3"; function removeVar($var, $query_string) { return preg_repl ...

Establish accuracy on additional inputs through directives when button is clicked within AngularJS

I lack familiarity with AngularJS directives because I typically rely on controllers. Can directives be used to set validity on other inputs? Specifically, I am trying to set validity on a certain input text when a button is clicked, but I can't figur ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...