Use Regular Expressions to escape a quotation mark inside a pattern

Looking for a way to replace double quotes within specific characters in a String. Here's an example string:

"XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>"

The desired output is:

"XML": "<MyTag>\"Value1\"</MyTag><MyTag2>Value2</MyTag2>"

Attempts with regexr to match the quotes have been unsuccessful like:

/<MyTag>(")<\/MyTag>/

/(<MyTag>)"(<\/MyTag>)/

Can quotes between tags be escaped?

Answer №1

When dealing with a very specific scenario, like the one you described, using a simple replace() function can be a more efficient and resource-friendly solution:

var str = '"XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>"';

// replace
str = str.replace('<MyTag>"','<MyTag>\\"');
str = str.replace('"</MyTag>', '\\"<MyTag>');

// test
alert(str);

You can also find this code on JSFiddle:
https://jsfiddle.net/xbe1x0mz/

Answer №2

let myString = '"<MyTag>"content1"</MyTag><MyTag>content2</MyTag>"';
let firstReplace = myString.replace(/<MyTag>"/g, "<MyTag>\\\"");
let secondReplace = myString.replace(/"</MyTag>/g, "\\\"<MyTag>");
// secondReplace = "<MyTag>\"content1\"</MyTag><MyTag>content2</MyTag>";

Answer №3

Avoid using regular expressions to manipulate XML data. It's much better to follow these simple steps:

// Convert XML string to DOM:
var rootNode = new DOMParser().parseFromString(XML_DATA, 'text/xml');

// Manipulate desired elements:
var tags = rootNode.querySelectorAll('DesiredTag');
for (var j = 0; j < tags.length; j++) {
    var tag = tags[j];
    tag.textContent = tag.textContent.replace(...);
}

// Convert modified DOM back to XML string:
var updatedXML = new XMLSerializer().serializeToString(rootNode);

Check out:

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

Incorporating a variety of classes by utilizing loops

Looking to add a class to specific li elements - the 1st, 4th, and 7th, the 2nd, 5th, and 8th, and the 3rd, 6th, and 9th. Is this possible? Is there a way to achieve this? ...

Is there a way to use StringTokenizer in JAVA for multiple tokens consisting of more than one character?

Looking to split a string based on multiple delimiters, some of which may consist of multiple characters. Here's an example: word1:word2|word3||word4|word5|||word6|word7 I want to tokenize the above string using delimiters such as ':', & ...

Troubleshooting problem with Bootstrap tabs and jQuery event triggering

Being new to JavaScript and jQuery, I am encountering issues with some basic things. I have set up 3 bootstrap tabs: (mainstream, substream, delayedstream). Within each tab, I have included a VLC player using jQuery, and the players are functioning perfec ...

Tips for avoiding errors caused by chart adjustments in Angular.js

I have two different perspectives, view A and view B. In view A, I present my chart. However, upon transitioning to view B, I encounter a quick error. It seems that this error arises due to a setTimeout function not being completed before the view change o ...

Vue 3's "<Component :is="">" feature magically transforms camelCase into lowercase

Within my application, I have implemented a feature where users can customize the appearance of social media links on their page by defining which platforms they want to include. Each social media platform is represented by its own component responsible fo ...

Using several materials on a single mesh in Three.js is a common practice

I am exploring ways to enhance a mesh by adding multiple materials. My goal is to layer a slightly transparent material on top of the existing one, allowing for opacity animation between the two. However, when I try to pass them as an array, the mesh simpl ...

How to attach a listener to an ASP.NET control with jQuery

Looking for a way to detect user interaction with a checkbook list, text box, or drop down list, and style other elements based on the values present. Is there a way to achieve this using jQuery? ...

When trying to convert a function component to a class component, using `npm init react-app` may result in the error `ReferenceError: React is not defined no-undef`

After running npm init react-app appname, I noticed that the file App.js was created, containing a function component: function App() { return ( <SomeJSX /> ); } I decided to change this function component into a class component like this: c ...

Vue.js - Implementing multiple values (array) for a component through a property

I am currently working with vue.js components that receive their data from external sources. For example: <vue-button icon="fa-arrow-right" text="mytext"></vue-button> Initially, this setup is effective. However, I encountered a challenge wh ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

determining the total invoice amount and the quantity of items in a React array of objects

Currently, I am working on an online shopping app built in React. Within this app, there is an Invoice array named invItems, which contains various products referred to as items. My goal is to calculate the total price by multiplying the quantity of each i ...

Tips for uploading a webform with a file via Jquery/Ajax to a webmethod

Is it feasible? I have a webform with textboxes and a file upload section. I am attempting to send the data to a web method using the .ajax() method. It appears that sending file content to the web method in this way may not be achievable as I am unable to ...

Creating dynamic keys to insert objects

In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision: ARRAY KEY OBJECT OBJECT KEY OBJECT ...

Unable to transform into a tangible entity

When I run the code below, I encountered an error stating: Uncaught exception: TypeError: Cannot convert 'validation.messages.field' to object $.fn.validate = function(validation) { $.each(validation.rules, function(field, fieldRules){ ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

The property 'scrollHeight' is undefined and cannot be read

I've created a messaging system using javascript and php, but I'm facing an issue. When new messages are received or the chat log grows longer, it creates a scrollbar. The problem is that when a new message arrives, the user has to manually scrol ...

Deploying and operating passport express node on azure: A comprehensive guide

I am currently developing an express node service for Single Sign-On (SSO) using the passport OAuth2 strategy. Here is the structure of my express node application code: AUTH - certs server.cert server.key -index.html -index.js (creates app as expr ...

What is the reason behind encountering these errors while trying to run my Gatsby development server?

I'm currently working on the part three tutorial provided by Gatsby on their official website and I've encountered a problem. Upon executing the command gatsby new tutorial-part-three https://github.com/gatsbyjs/gatsby-starter-hello-world I rec ...

Generate a random color using Javascript on every page load

Using JavaScript, I am dynamically creating a graph based on a Bootstrap template. This particular graph displays various appointment types and their corresponding values. try { //bar chart var ctx = document.getElementById("ReferralTypeWeekly"); ...

Having trouble with JavaScript's variable scoping?

Currently, I am using Node.js and mongoose, but I have encountered a challenging issue: var dbvar; doc_model .findOne({aadhar}) .then(()=>{ dbvar=1; }); paramedic_model .findOne({aadhar}) .then(()=>{ dbvar=2; }); console.log(dbva ...