Using regular expressions to eliminate text located outside of the tags within a string

Presented is a string consisting of an XML string below:

 var xmlString = "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>";

I am seeking assistance on how to eliminate text that lies outside the tags (text not enclosed by any tag) using regular expressions. Can anyone help me with this?

Answer №1

If you are faced with the task of extracting text that is not enclosed within an HTML element, provided that the code is well-formed and does not contain incorrect strings like

var str= "<str>lorem <b>ipsum</str>";

You can achieve this using a regular expression such as the one below:

var str= "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>",
    elements = str.match(/<(.+?)>[^<]+<\/\1>/gi);

console.log(elements.join(''));

The output of this would be:

<str>rvrv</str><q1>vrvv</q1><q2>rtvrvr</q2>

Please note that in order to detect closing tags, a backreference was used (refer to )

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

Tips for displaying data by using the append() function when the page is scrolled to the bottom

How can I use the append() function to display data when scrolling to the bottom of the page? Initially, when you load the page index.php, it will display 88888 and more br tags When you scroll to the bottom of the page, I want to show 88888 and more br ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

Searching the database to find if the username is already in use with MEAN

Help needed with signup controller code! app.controller('SignupController', function ($scope, $http, $window) { $scope.submitSignup = function () { var newUser = { username: $scope.username, ...

Execute a PHP function when a post is clicked using JavaScript

I have a script that shows an image depending on database results. When a user clicks the image, it changes to a new one. The green_star signifies that both $user_id and $thedb_id are in the database, while the grey_star indicates they are not. I want to b ...

Error: Undefined variable in JavaScript obfuscation

My website has several small JavaScript files that I currently merge into one file and then minimize using terser. The website functions perfectly with the minimized version. Now, I want to take it a step further and obfuscate the code using JavaScript-Ob ...

Whenever I work with NPM, node.js, and discord.js, I consistently encounter the error message stating "TypeError: Cannot read property 'setPresence' of null."

I'm developing a Discord bot with NPM and discord.js, but I keep encountering an error that says "TypeError: Cannot read property 'setPresence' of null". Here is my bot code: const Discord = require('discord.js'); const { prefix, ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

What is the best way to call a JavaScript function within a PHP echo statement that outputs a <div> element?

Having trouble echoing this PHP code due to issues with single quotes, causing the HTML to end prematurely. Any suggestions on how to fix this? function button($conn){ $sql = "SELECT * FROM table"; $result= mysqli_query($conn, $sql); while($r ...

Unable to send messages despite successful connection through Sockets.io

My Java Server is set up to listen for messages from an Ionic 2 Client using Sockets.io. The server can successfully send messages to the client, but I am facing issues with getting the client to send messages back to the server. For example, when the jav ...

Utilizing PHP configurations in JavaScript with AJAX for JSON implementation

Trying to have a config.inc.php file shared between PHP and JavaScript seems to work, but when using ajax, the "error-function" is always triggered. Is there a way to successfully share the config file with working ajax implementation? This is being utili ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

Guide on passing a JSON body as a string in a PUT API request using Fetch in a React.js application

How can I pass a JSON body as a string in a FETCH PUT API in React JS? I am attempting to add 20 to the Balance like this: Balance: details[0].Balance.toString() + 20, but it is not working as expected. I want the entire result to be a string. Any assista ...

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

JavaScript code to alter the timeout duration for image changes: Update

I am working on a fun project that involves alternating between two images, one green and the other black. Here is the code snippet: <script> var switchImage = 1; var delayTime = 500; switchImages() function switchImages() { if (switchImage == 1) ...

Error: Unable to locate module '@material-ui/lab/TabContext' in the directory '/home/sanika/Desktop/Coding/React/my-forms/src/Components'

Hello everyone! I recently started working with ReactJs and I'm currently facing an issue while trying to implement TabContext using the material UI library in React. Upon debugging, I suspect that the error might be related to the path configuration. ...

An easy CSS conundrum when hovering

Looking for some assistance with CSS. I want to display the text "Featured Page" with a picture appearing on the right side upon hovering (mouseover). Currently, the picture shows up under the text using the following CSS, but I need it to be larger and pl ...

Verify if the user is currently inputting text within a specific range of characters within

I am dealing with a specific issue involving a textarea. By default, this textarea contains a string of any type, but a user is only able to type inside opening and closing brackets. For example, "Leave[]" allows typing within the brackets but not outsid ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

Identifying the presence of node.js on your system

After installing node.js, I found myself at a loss on how to run applications. Despite the lack of instructions, I was determined to test if it was working by executing a script named hello.js: console.log('hello world'); I couldn't help b ...