AngularJS substitution with regular expressions

Looking to replace specific words in HTML content within <div> and <p> tags upon page load. Utilizing angularJS to achieve this task.

This is my current function:

var elementsList = e.find('p');

var regex = ('[^<>\\n]*?\\b(Cat|Dog|Fish)\\b[^<>\\n]*?', 'gi');                 

angular.forEach(elementsList, function(_element){
    var eHtml = $(_element).html();
    e.html(eHtml .replace(regex, function(fullMatch, match){
    if(angular.isString(match))
    {
         return 'TEST' + match;
    }
    }));
    $compile($(_element).html())($scope);
  });                                                                 

$compile(e.contents())($scope);

However, I'm facing an issue where the HTML is not being updated correctly. Instead of just replacing the matched word, it replaces the entire sentence.

For instance, if the original HTML is:

<p>I am a dog.</p>
<p>I am a cat.</p>
<p>I am not a dog but a cat.</p>

I want the desired output to be:

<p>I am a TESTdog.</p>
<p>I am a TESTcat.</p>
<p>I am not a TESTdog but a TESTcat.</p>

Answer №1

It appears that there is a misunderstanding between the element and the full HTML, specifically in regards to the <p> tag.

In this code snippet:

angular.forEach(elementsList, function(_element){

You are accessing the elementsList, which contains <p> tags, and the _element refers to a specific <p> tag from this list. However, you then retrieve the HTML content of this element:

var eHtml = $(_element).html();

Afterwards, you perform a replacement:

eHtml.replace(regex, function(fullMatch, match){ ... })

and insert it into the main e element:

e.html(eHtml.replace(...))

Instead of replacing the HTML for a specific tag, you are replacing the entire HTML content with each iteration.

Consider using $(_element) instead of just e:

$(_element).html(eHtml.replace(...))

UPDATE: Your regex can be simplified to:

/\b(Cat|Dog|Fish)\b/gi

and can be applied as follows:

var regex = /\b(Cat|Dog|Fish)\b/gi;
$(_element).html(eHtml.replace(regex, "Test$1"));

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

Handling asynchronous behavior in the context of conditional statements can be a challenging aspect of

Currently, this code section is passing undefined to if(customerWaiting >0). It's an async issue that I'm struggling to resolve. Despite my efforts and research on other threads, I can't seem to make this basic newbie question work. I&a ...

Is there a way to programmatically toggle a button's enabled state depending on the content of a text input field?

I want to create a functionality where a button will be enabled if the value in a textbox is 'mypassword'. If it's not equal to 'mypassword', then the button should be disabled. I've attempted the code below, but it doesn&apos ...

Error: HTMLAnchorElement.linkAction is attempting to access an undefined property 'add', resulting in an uncaught TypeError

Displaying the following: Error: Cannot read property 'add' of undefined at HTMLAnchorElement.linkAction const navigationLinks = document.querySelectorAll('.nav__link') function handleLinkAction(){ // Activate link navLin ...

What is the best way to populate a div with multiple other div elements?

My current project involves creating a sketchpad using jQuery for an Odin Project assignment. However, I have encountered an issue with filling the canvas (wrapper div) with pixels (pixel divs). The canvas does not populate correctly. Here is the link to m ...

Sending a parameter value when onClick function is called

Currently, I am learning React JS and facing a challenge with passing parameters (like button ID or tab value) to the Tab onClick event. It appears that I'm receiving 'undefined' results when trying to pass attribute names as parameters. Ple ...

Properties that cannot be modified, known as read-only properties,

While browsing through this post on read-only properties, I stumbled upon the following code snippet: var myObject = { get readOnlyProperty() { return 42; } }; alert(myObject.readOnlyProperty); // 42 myObject.readOnlyProperty = 5; // Assignment al ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

Attempting to extract the data from SweetAlert

I've been attempting to retrieve the return value from sweetalert, but I encountered this: Promise {<pending>} >__proto_:Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]:true resulting from this piece of code: var ret = swal({ ...

Using Twitter bootstrap with Node.js and Express framework

Is it possible to integrate Twitter Bootstrap with Node.js and Express? I understand that I need to place CSS and Javascript files in the ./public directory (if it's set as default). However, when trying to implement Twitter Bootstrap on Node.js and ...

Exploring the Power of AngularJS' $resource with JAX-RS Integration

Recently, I developed a small web application using AngularJS, JAX-RS, and Hibernate. While I am able to retrieve objects of my type 'Plugin' successfully, I am facing issues with saving them. Upon inspecting the object on the server, I noticed t ...

There is an issue with the JSON format being received by fetch in JS when using json_encode in php

Recently, I encountered an issue with my JavaScript function that retrieves data from a PHP page. In the JS code block: fetch("print.php) .then(function (r) { return r.json() }) .then(function (values) { ...... ...... ...

Access a webpage in an html document using URL variables

In the process of developing an MVC web app without utilizing any MVC framework, I have created an index.html file with a section that dynamically loads all the views as needed by the user. However, I encountered an issue where direct URLs such as www.foo. ...

Help! My express.js query is not functioning properly

I am facing an issue with a query in express.js. Citta_p and Citta_a are two arrays, and I need my query to return all the IDs for cities. However, it seems that only the last value is being returned, as if my cycle starts from var i = 1 and skips the valu ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

Can you please explain the significance of (session?._id)?

export default NextAuth({ ... callbacks: { session: async ({ session, token }) => { if (session?.user) { session.user.id = token.uid; } return session; }, jwt: async ({ user, token }) => { if (user) { ...

What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks: When the 'all' option is selected in either of the mat-select e ...

Executing a function after the completion of another

Here is my function: function functionName($results) { //do some stuff disableSave() } When this function runs, I want to call the enableSave() function. How can I achieve this? I attempted to pass the function as a callback but I am unsure wher ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

What is the best way to trigger a method once an image has completed loading and rendering?

Is there a way to trigger a method once an image has finished loading and displaying on the web browser? Here's a quick example using a large image: http://jsfiddle.net/2cLm4epv/ <img width="500px" src="http://www.digivill.net/~binary/wall-cover ...