Ways to extract code within delimiters

After loading a template from a file, the structure is as follows:

[[style]].someclass{padding:10px 15px}[[/style]]
[[code]]<tr><td class="someclass">{{text}}</td></tr>[[/code]]

The template is loaded using .get() and stored in the "template" variable:

$.get('template.html', function(template) {
 if (template) {
   //extract css styles from [[style]]..[[/style]] etc.
 }
});

How can I extract the content between these markers?

I simply need to assign the contents within the blocks ([[style]]..[[/style]], [[code]]..[/code]]) to relevant variables like var style = ..., var code = ... :)

P.S. I hope my explanation makes sense... Apologies for any language issues :)

Answer №1

[[code]] and [[style]] are not recognized as standard markup language tags. Because they are not treated as DOM elements, you cannot simply use basic jQuery methods to navigate through them.

One way to handle this is by using Regular Expressions, where you can extract the contents of each code and style block and store them in separate arrays:

$.get('template.html', function (template) {
    var codeReg = /\[\[code]]([\s\S]*?)\[\[\/code]]/g,
        styleReg = /\[\[style]]([\s\S]*?)\[\[\/style]]/g,
        codes = [],
        styles = [],
        item;
    while (item = codeReg.exec(template))
        codes.push(item[1]);
    while (item = styleReg.exec(template))
        styles.push(item[1]);
    console.log(codes);
    console.log(styles);
});

Click here for a live example. (Please note that I am using $.post in this example because JSFiddle does not support $.get for their /echo/html/ utility.)

For further reading:

Regular Expressions reference

Best way to store JS Regex capturing groups in array?

edit: I have replaced the meta-character . with [\s\S] in the (.*?) pattern to match all white space characters including new lines and non-white space characters. Reference

Answer №2

Get Creative with HTML and CSS using jQuery!

If you're looking to change or retrieve inner HTML content in your web page, jQuery is the way to go:

Check out the jQuery HTML function

To make this process smooth sailing, be sure to master jQuery selectors:

Learn more about jQuery Selectors here

Explore specific selectors like:

Class Selectors

Element Selectors

Add Style with CSS

You can also use jQuery to manipulate CSS within your <style> tags. Make use of the same selectors discussed above along with these functions:

Discover various jQuery CSS functions

Utilize the jQuery CSS function for added control

Answer №3

Modify the content inside a code tag:

$("code").html("*insert your desired text here*");

Adjust the styling of an element using CSS properties. You can target elements by id (using '#'), class (using '.'), or type (like "body", "code", "div"). It's recommended to use CSS instead of changing the HTML directly:

$("*element*").css({*property*: *value*, *property*: *value*});
$(".*class*").css({*property*: *value*, *property*: *value*});
$("#*id*").css({*property*: *value*, *property*: *value*});

*You are free to customize anything enclosed in asterisks*

If you have any questions, feel free to ask in the comments section.

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

Using Angular Ionic 3 to apply the disabled attribute

I have a situation in my main.ts where I need to disable a textarea in the HTML if an object is initialized. I've attempted various methods like: ng-attr-disabled="!myObj"; ng-attr-disabled="{myObj!= null}"; and also directly using ng-disabled. I e ...

What is the process for modifying CSS in Laravel?

New to Laravel over here, currently working in Homestead. When I need to make changes to my CSS, I typically edit the app.scss file located in resources/assets/sass and then recompile the css with Mix using the command npm run dev. I'm not entirely ...

Error: Bootstrap/CSS not functioning properly on IE and ED browsers

Currently, I am tackling a web application project, and much to my surprise, I discovered that the CSS/bootstrap is not functioning properly on Internet Explorer and Microsoft Edge. Despite attempting various solutions found on Stack Overflow, none seem to ...

Angular dynamically filling in a table with incomplete object data

I am currently working on a scientific project that involves displaying large amounts of data in tables. The experiments I'm working with have timestamps that follow this format: interface TimeData { time: string; data: {SD: string, SEM: string ...

Adding a text field on top of a div based on the dropdown value selection

I am working with a dropdown option inside a div. I want to make it so that when the last option is selected, a text box will appear on top of the dropdown. And when a different option is selected, the text box should be disabled. How can I achieve this? ...

Choosing based on conditions within a function

I am currently working with an object that contains orders from a restaurant. var obj = { orders: [ null, { date: "2018-07-09 10:07:18", orderVerified : true, item: [ { name ...

A guide on leveraging console.log in Next.js

I'm having trouble displaying the output of an API call using console.log. The issue is that nothing appears in the console (both in the browser and Visual Studio Code). The only console.log that seems to work is within the RouteStatus function, but i ...

Having troubles with the rendering of views and layouts in FlightPHP Framework

I have recently started using FlightPHP for a small website project. My approach involves utilizing views and layouts to render the various web pages: <?php require 'flight/Flight.php'; Flight::route('/', function(){ ...

When employing .wrapAll, the child element's width is disregarded

Visit this WordPress site where the client has a unique setup with multiple pages showcasing images one after another. To achieve the desired layout, jQuery is utilized to wrap each image in a div element with a class of .postImg: Here's the script: ...

Fluid Grid System with columns of specific dimensions

Recently delving into the world of Foundation Framework, I've just begun utilizing it for my projects. My current task involves crafting a responsive design with the help of the Foundation Grid system. Specifically, I've set up a grid layout for ...

Error: The specified key is already present in the object store

I am currently utilizing React 16.3.2, Redux 4, and Dexie 2.0.3. Every time I attempt to store data for the second time, an error message is thrown. Error: ConstraintError: Key already exists in the object store. return dispatch => { db.ta ...

Notify when a value in a PHP database table is modified

Within my setup, two sheets are utilized. The control sheet showcases a list of job details along with a column that mirrors the notes linked to the active job. On the other hand, the second sheet allows operators to attach new notes. The primary task at ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

Hexagonal border with embedded image

I'm striving to achieve the image below: https://i.sstatic.net/iZIex.png I've managed to create a hexagon border and text, but I'm unsure how to incorporate the hexagon image and create a grid of 3 hexagons. Any assistance would be greatl ...

Tips for updating a list of orders using keywords entered in a text input field

I have a collection of car objects and an input field that triggers a change event. When the value in the input field is updated, I want to reorganize the order of the cars. For example, if I enter "Tau" in the input box, I want the ford object to be plac ...

Pager.js utilizing Deferred Bindings

I am currently working on using Pager.js to develop a single page application. The structure I have set up is as follows: #word/definition #word/example #word/synonym This means that definition, example, and other elements are divs with page bindings: & ...

Transferring drag-and-drop modifications made with JQuery to a document using AJAX

Lately, I have utilized JQuery to rearrange table rows on a webpage and transmit those modifications to an external script via Ajax. The table rows are extracted in a certain order from a database that includes a field named "Position" with a numerical val ...

What is the best way to connect two buttons in separate divs?

I'm facing a challenge of adding two buttons side by side when they are located in different div elements. I've tried using the float property in the btn-group, but it interferes with the functionality of the dropdown and affects the animation. H ...

Triggering a click event on an anchor <a> element

Seeking help with a Javascript event query. I have an <a> tag set up like this: <a id='aTag' href='http://example.com'>Click to redirect</a> When attempting to trigger the click event using: <script> $('#a ...

Retrieving information from a database using PHP PDO to populate a dropdown list

On my HTML page, I have a form that allows users to insert data into the database. Some fields in the form require dropdown lists, and I want to populate these dropdowns with data from the database. Previously, I had hardcoded the dropdown options like th ...