Leveraging Dynamic Information within a Regex Pattern

I have a unique collection that appears as follows:

listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"]

The website displays a textArea for users to input data like :-

Hello, I really enjoy studying <<English>> 
or
My favorite subject is <<Biology>>, it's the best 

If a user enters anything other than what's in the listA between the <<>>, I want to display a validation error message with the remaining content being customizable.

I attempted to use regular expressions and directives but couldn't quite get it right. Please let me know if you need further explanation

This is my current attempt :

checkText(event) {
    // const regex = /(?:^|\s)<<(.*?)>>(?:\s|$)/g;
    var str = this.editClauseObj.textObj.text;
    console.log("str",str);

    let name_val = 'Name';
    const regex = /^([a-zA-Z]*\s)*[<<name_val>>]*\s*[a-zA-Z\s]*$/g

    if (!regex.test(str)) {
      this.showError = true;
      this.errorMessage = "Please enter a valid value inside <<>>"
      console.log("test", this.showError);

    } else {
      // do something else
      this.showError = false;
    }
}

Answer №1

const subjectList = ["Physics","English","Chemistry","Biology","History","Human Values","None"];

const message = "Hello, My favorite subject is <<English>> \n I enjoy learning about <<Biology>>, it's fascinating \n I also like <<History>>, it's interesting ";

// Extract text within << and >> delimiters
const regex = /<<([^>>]+)>>/g

let foundSubjects=[];

while( currentSubject = regex.exec( message ) ) {
    foundSubjects.push( currentSubject[1] );
}

// Display all subjects found in the message
console.log(foundSubjects);

// Filter out subjects not present in the listA
var finalSubjects = foundSubjects.filter(function(subject) {
  return !subjectList.includes(subject);
});


console.log(finalSubjects);

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

Can you explain the distinctions among 'data:', 'data: ()', and 'data()' when working with Vue.js?

While exploring the Vue.js documentation, I came across two ways to define data: data: {} and data() { return; }. data: { defaultLayout: 'default' } data() { return { defaultLayout: 'default' } } However, there is ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

What is the method for including HTML special characters in d3.js?

I am attempting to incorporate the degree symbol in my HTML code using ° const degreeNum = d3 .select(`#windBox${order}`) .append("text") .attr("x", 250) .attr("y", 130) .style("font", "bold 50px sans-serif") ...

Using JavaScript to redirect browser with a specific string

My goal is to redirect all users who visit a specific URL to another page. While this redirection works effectively, I now need to implement it with a tracking URL. The issue arises when Javascript automatically adds a "/" in front of the tracking string ...

How can I switch the header bar button from "login" to "logout" in a React

I am currently working on a React and Next.js frontend template, specifically focusing on creating a dashboard with a header bar and login button. Once a user logs in, the login button should change to a logout button and the links in the header should als ...

TypeScript incorporates a variety of @types versions for react

I made changes to my compilerOptions within the tsconfig.json file with the specified paths "paths": { "react": ["node_modules/@types/react"], "@types/react": ["node_modules/@types/react"] } However, I noticed that @types/react-router is using its o ...

My instance transforms with the arrival of a JSON file

I'm grappling with a query about data types in TypeScript and Angular 2. I defined a class in TypeScript export class product{ public id:number; public name:string; public status:boolean; constructor(){} } and I initialize an instanc ...

Is there a way to include two functions within a single ng-click event?

Is it possible to incorporate two functions in a single ng-click event? Below is the code snippet: <button class="cButtonSpeichern" ng-click="saveUser()">Speichern</button> In addition, I would like to include this function as well. alert ...

Navigating an array of JSON objects with the http client and Observables in Angular: A Step-by-Step Guide

Here is the URL I want to make an HTTP request from a service in Angular: The data consists of an Object containing an array of Features. The Features array includes 4 Objects - type, properties, geometry, and id. I aim to store the properties and geomet ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Issues with AJAX chat system functionality

I've been struggling with this issue for a while now. Despite rewriting the code multiple times, I can't seem to make any progress. Below is the JavaScript code (located on the same page as the HTML): Summary: The user inputs text into a box, w ...

manipulating data using javascript

I have an array of objects like this: var arr = [{'name':'one','age':24},{'name':'two','age':21}] Then I assigned this array to another variable var newVar = arr. Next, I modified the value of a ...

An unexpected identifier error occurred following an Ajax request

Below is the HTML code that I am working with: <div id="texttheory" class="centertext">'. $short .' </div>'; <button id="thbutton" class="theory_button" onclick="javascript:changetheory('.$long.')"> <im ...

The re-rendering in React useEffect() is occurring, but the screen is not updating with the dynamic value

How can I make the state value increment when clicking the "+" sign? Even though the useEffect is running, the updated state value is not being displayed on the screen. Initial state : const italianMenu = [ { name: "White Sauce Pasta", ...

Is it possible to execute a function once an element has finished loading?

I am facing a challenge with running the List_Sandbox functions after a specific each loop. This loop selects checkboxes that trigger a change event, rendering additional checkboxes that need to be selected. The issue arises when the List_Sandbox functio ...

In nodejs, I am looking to update a specific string in numerous file names

I need to update a specific string in file names. Using glob and path, I'm able to extract multiple file names from various directories. Now, my goal is to rename these files from abcd-change-name.js to abcd-name-changed.js. Here's the progress ...

Update the URL every time the user clicks with JavaScript and HTML

Welcome to my website at Inside, I have this JavaScript code: function updateStyleSheet(sheet){ document.getElementById('pagestyle').setAttribute('href', sheet); And in my HTML, you can find: <li><a href="#" onclick="update ...

The busboy does not have the ability to receive any uploaded files

My form utilizes ng-flow for managing file uploads: <form class="form-horizontal" enctype="multipart/form-data"> <div flow-init="{target: '/test', testChunks: false, query: {'_csrf': '{{csrf}}', 'somestring& ...

The jquery fancybox ajax modal popup fails to display in Internet Explorer 7

Recently, I utilized JQuery fancy box for the first time to display a menu list. When clicking on a specific item, the page is rendered properly in an iframe. However, if there is already an AJAX model popup present on the rendered page, it doesn't di ...

Error encountered when running shell command in JavaScript due to permission denial

I've been working on a JavaScript code to execute a shell command and open Notepad. Below is my current implementation: <script type="text/javascript"> function runNotepad() { var oShell = new ActiveXObject("Shell.Application"); ...