How to replace a substring in JavaScript only if it appears outside of quotes, not within them

/+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/g, "&&"

When working with regular expressions, I successfully used the above pattern to replace instances of '+' with '&&'. However, now I am wondering how to modify it to replace the string "and" with "&&". Any suggestions?

str = "Loop(this and that is "Help and enjoy")";

The desired output should be:

Loop(this && that is "Help and enjoy")

Answer №1

Did you attempt to simply substitute +?

/(?:and)(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/g, "&&"

Answer №2

One method to accomplish this task is by identifying content enclosed in double quotes prior to:

var corrections = {"and": "&&", "+": "&&"};

string.replace(/"[^"]+"|\+|\band\b/g, function(match) {
    return corrections[match] || match;
});

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

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

How can I run global $PATH binaries as a no-home user using sudo?

When executing web-server-context-only operations, I run commands using sudo -u www-data {command}. Despite having NodeJS globally installed and in the root's path, it fails because the user www-data has a different path: /usr/local/bin. If I create a ...

Issue with inheritance from Angular ModalCtrl to ServiceCtrl not functioning as expected

I've been working on linking models to services in order to update global models throughout my app, but it doesn't seem to be functioning as expected. Recently, I delved into AngularJS and I suspect that I may have misunderstood my code. From wh ...

Utilizing Cpanel to trigger the loading of PHP content upon button click

I have designed a custom template for a cpanel business website. I am looking to implement functionality where clicking the "Add product" button loads another PHP file into the gray area on the page. This gray area is represented by a div element. Is there ...

Modify the icon in the header of MaterializeCSS Collapsible when it is opened

I'm struggling to figure out how to change the icon of a toggled collapsible element. I have been reviewing their documentation but am having trouble making it work as intended. $('.collaps_roles_permission').collapsible({ accordion: tr ...

HTML display with two columns for books viewing

My Plan: I am working on incorporating HTML content from an external source into my app, displayed in a 2-column horizontal scrolling book format using a WebView element. I want it to resemble how the Edge browser presents an EPUB book, with seamless horiz ...

Changing the cursor while the onDrag event is active in ReactJs

I want to implement Drag functionality on certain elements in my application, but I am facing an issue where the cursor changes during dragging. How can I change the cursor specifically when onDrag is active? ...

Iterate through an array to dynamically assign values to variables using string elements

I'm facing a challenge here. I need to generate 4 new elements with the same class but different IDs without repeating code. Unfortunately, my loop doesn't seem to be working as expected. I've spent the last 2 hours trying to crack this puz ...

Include a Custom Button with an Optional Event Handler

I've created a customized material-ui button component: type ButtonProps = { disabled: boolean; text: string }; export function CustomButton({ disabled, text }: ButtonProps) { return ( <Button type="submit" disabled={disabled} ...

Using Jquery to search for an element within a variable and update the text

Having trouble with the following expression: (not even with .text()) $(file.previewElement).find('[data-dz-name]').html(file.name); The variable File.previewElement is defined as: $(".preview-template").html(); The debugger output for $(file. ...

Unable to retrieve a value after deactivating a Div element

I have created a web page using MVC Razor. On this page, I included a div element with the following structure: <div class="row" id="DivDisableForView"> <div class="col-md-4"> <label for="" class="control-label" ...

Attempting to execute AJAX using jQuery is proving to be unsuccessful

I am experimenting with AJAX and jQuery. Here is the code I am working on: <div class="form"> <form name="contact" class="js-form-contact" action="contact.php" method="post"> <div class="clearfix"> ...

a popup window that appears upon clicking a linked button

<td colspan ="2" style="width: 64px"> <div style="float:left; padding-left:9px;"> <asp:LinkButton ID="lnkremoveloc" runat="server" OnClick="lnkremoveloc_Click" CssClass="linkclass" style="cursor:pointer" ...

Navigating with React to a specific endpoint does not display the expected content

When I navigate to another endpoint, the component content only shows up after manually refreshing the page. I have come across similar inquiries on various platforms such as Stack Overflow and here. I have also consulted the React Router documentation an ...

Developing a model in NodeJS poses a challenge for me

While attempting to create a model in NodeJS const mongoose = require ('mongoose'); const User = mongoose.model('User',{ name:{ type:string }, lastname:{ type:string }, age: { type:Number } }) module.exports = User; **errorIS ** C: ...

The React application has been launched, however, the images stored in the directory (/assets/images/) appear to be

My React.js app has been successfully published, but the images assets located in the images directory (/assets/images/) are not being deployed. The structure of the published site is shown here: https://i.sstatic.net/c0zow.png After running the command ...

Unable to loop through a list in JavaScript

<script type="text/javascript"> window.onload = function () { for (var i=0;i<@Model.listsinfo.Count;i++) { $('#work').append($('<div class="col-md-3" id="temp"><label for="tex ...

Import 3D models and textures from a multipart file into three.js using Collada format

I am facing a challenge with loading Collada and image data stored in a multipart file outputted from an application. My goal is to display the Collada object and its associated images using three.js on the Web. However, I'm unsure if three.js can int ...

When the user first scrolls down, a popup will appear. However, if they scroll down a second time,

I'm attempting to create a popup that appears when the user scrolls down to a certain point. The code for this functionality is working well and is provided below. <div id="spopup" style="display: none;" class="news_sletter"> <a style="p ...

Track the movement of the mouse to illuminate objects in a three.js environment

Recently delving into the realm of three.js, I am seeking to achieve a solution reminiscent of this older thread with a slight tweak. The objective is to have a stationary sphere at the center of the scene while having the point light in the scene track t ...