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

Retrieve a Vue Component by utilizing a personalized rendering method for a Contentful embedded entry

Currently experimenting with Contentful, encountering some issues with the Rich text content field. To customize the rendering of this block and incorporate assets and linked references in Rich text content, I am utilizing the modules '@contentful/ri ...

What is the significance of the term "Object object"?

I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick) is clicked. There are [Object object] elements in the array. The last line ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

How can I set up multiselect values in AngularJS ui-select?

Solution: Success! I managed to resolve the issue by implementing this solution and creating a customized build of the ui-select. Hopefully, this fix will be incorporated into the official master branch soon! Issue Is there a way to set up a select elem ...

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

The concept of undefined functions and the use of dependency injection may not always align

Recently starting with AngularJs, I am honing my skills by developing a single page Todo Application. However, I have encountered an issue while trying to load a localStorage factory that I intend to use for this project. Currently, I am stuck on the error ...

Repeated attempts to initiate ajax script failing to function

I am completely new to the world of Ajax, having just started learning about it a few days ago. Despite my lack of experience, I need to incorporate it into a form that I am creating for my employer. Unfortunately, I have been facing difficulties in getti ...

Exploring search filters using KnockoutJS

I'm currently working on incorporating a search filter into my web application. After reading some informative articles and exploring various Jsfiddles, I've attempted to enable searching by TypeName to display the corresponding row with that spe ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

JavaScript code using the Jquery library to retrieve the following article from 'cached memory'

I am aware of the easier CSS options for my question, but I am determined to learn JS (Jquery), so please bear with me. My plan: Menu-items are connected to articles within my content division. Initially, only the first article (#intro) is displayed. All ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

the ng-click event handler is not triggering the function

<body ng-app="groupChatApp" ng-controller="groupChatController"> <div id="error-container">{{errorValue}}</div> <div ng-model="changeForm" id="changeForm"> <input id="name" type="text" name="name" value="" placeho ...

What is the best way to retrieve the value of the 'body' object from a Slim_Http_Request Object?

Within my angular application, I have implemented the slim framework as a server. I am facing an issue capturing the body value from the Slim_Http_Request Object. Here is a snippet of my app.js code: MyApp.controller('Remove', function($scope,$ ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Utilizing AngularJS to iterate through an array of dictionaries

Within a specific section of my HTML code, I am initializing a scope variable like this: $scope.my_data = [ { c1: "r1c1", c2: "r1c2", c3: "r1c3", ...

An error was encountered with Ajax and JSONP due to an unexpected token causing a SyntaxError

Currently attempting to retrieve information from the host at 000webhost The data is in JSONP format: { "categories": { "category": [ { "name": "Android", "parent": "Computer Science", "ID": "2323" }, { ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...