Looking to Search For a String Using Regex in Javascript?

I am encountering a string that looks like this: "No reservation is available to allocate within the group StorageGroup1. Total 330 GB of storage was requested"

However, sometimes I do not receive this exact string format, as the group name and total storage amount may vary. When I do get this specific format, I can confidently route the ticket to the correct group. What would be the most effective way to parse this information in order to extract the storage group name and the quantity, allowing me to create dynamic tickets?

Answer №1

let myText = "An available reservation is needed for allocation within the StorageGroup1 group. The requested storage amount is 330 GB.";
let myPattern = /An available reservation is needed for allocation within the StorageGroup(\d) group. The requested storage amount is (.*) GB./g;
let result = myPattern.exec(myText);
if (result != null) {
  let storageGroup = result[1];
  let sizeRequested = result[2];
}

You can adjust myPattern to suit your requirements, I included the full sentences in it for precautionary measures. http://jsfiddle.net/xbvpsp19/

UPDATE following @krispykream4's feedback: If the group name could change, you can use the following:

let myUpdatedText = "An available reservation is needed for allocation within the StorageGroup1 group. The requested storage amount is 330 GB.";
let myUpdatedPattern = /An available reservation is needed for allocation within the (\w*)(\d) group. The requested storage amount is (.*) GB./g;
let updatedResult = myUpdatedPattern.exec(myUpdatedText);
if (updatedResult != null) {
  let storageGroupName = updatedResult[1];
  let specificGroup = updatedResult[2];
  let storageSize = updatedResult[3];
}

http://jsfiddle.net/LhL0w232

Answer №2

Here is an example of how it will look:

let message = "No available reservations can be found in the StorageGroup1 group. A total of 330 GB storage was requested.";

let result = message.match(/\d+\sGB/)[0];

/\d+\sGB/ breakdown:

The pattern \d+ represents one or more digits, followed by a \s whitespace character, and finally ending with GB to indicate gigabytes.

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

Is there no "on" function available in the Node readline module?

I am currently working on building a Node.js application that reads a text file line by line using the 'readline' module and displays it in the console. var lineReader = require('readline'); lineReader.createInterface({ input: fs.cre ...

What is the process for integrating Internet Explorer 10 compatibility into a basic VueJs component?

I am facing an issue with a VueJs component that is not rendering in IE 10. Context: The Vue component I am working on is a company events list with basic filtering and sorting functionalities. Unfortunately, IE10 support is required for this project. Eve ...

Error message: "Unassigned value in knockout.js"

Here is my code snippet for binding to a textbox: var CategoryViewModel = { categoryModel: ko.observable({ categoryId: ko.observable(), categoryName: ko.observable(), active: ko.observable() }), GetCategoryById: functio ...

Having issues with the onclick _dopostback function in MVC? It seems like the post

When attempting to execute a postback in ASP.NET MVC after confirming with JavaScript, the following button is used: <input type="submit" id ="RemoveStatus" value="Remove Status" name="button" onclick="return CheckRemove();"/> The JavaScript code f ...

Exploring the methods to access GuildMember roles along with their respective details

const Discord = require('discord.js'); const bot3 = new Discord.Client(); const token3 = 'I am not disclosing my bot's token'; const mark2 = '*info personal' bot3.on('message', msg =>{ let args2 = msg.co ...

Challenges faced when subscribing to global events in JavaScript

I have some questions about the JavaScript code snippet below: What does .events.slice(-1)[0][0] signify? Similarly, could you explain the purpose of nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";? Could you elaborate on what is m ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

Strategies for obtaining multiple instances of duplicated data within an array object

this array contains multiple instances of duplicate data var = [{id: 1, name:'jeff'}{id:1, name:'kent'}{id:2, name:'ynez'}{id:2, name:'cloe'}{id:3, name:'Ron'}{id:3, name:'chester'}] to achieve ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Is it possible to refresh text in table without clearing icons?

Is there a way to maintain icons in table rows when editing text fields from a dialog? Currently, regardless of whether I use .html() or .text(), the icons disappear. I suspect that utilizing .content() may be a solution, but I'm unsure how to impleme ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

Unable to retrieve the "value" attribute from the DOM element of the plus/minus box

Looking to retrieve the "value" attribute from the selection box that allows users to choose the quantity of a specific item on my website. As a beginner in both Javascript and HTML, I noticed the attribute when inspecting the element: <input size="2" ...

What are some methods for enclosing DIV elements with distinct class names?

Similar Question: How to group paragraph elements inside a parent element? I am facing an issue with repeating HTML blocks in my document <!-- first block --> <div class="first"> My first div </div> <div class="second"> ...

What is the significance of h being undefined?

I have successfully set up a new Vue project using vue create and added Storybook with no issues. However, after installing storybook-addon-designs and following the instructions in the readme to add it to my story, I encountered an error in my console sa ...

JavaScript implementation causing Safari to display a blank page

After diving into JavaScript recently, I encountered some issues right away. I've been attempting to run a simple "Hello World" program but no success so far. Each time I open the html file in Safari, it displays only a blank page. Despite having enab ...

How can you achieve div scrolling in React by simply dragging the mouse?

I'm currently exploring options for scrolling through a div using mouse drag, but I haven't come across anything particularly helpful. Specifically, I'm trying to replicate the functionality found in Trello where you can horizontally scroll ...

Click to trigger image rotation with JavaScript

img { display: block; margin: 20px; width: 50px; height: 50px; } .crossRotate { -webkit-transition-duration: 1s; -moz-transition-duration: 1s; -o-transition-duration: 1s; transition-duration: 1s; -webkit-transition-property: -webkit-tran ...

Utilizing Vue.js: Dynamically linking v-model to route parameters depending on the current state

I'm currently in the process of developing an application that will serve as the backbone for a restaurant chain's website. The main functionality involves allowing users to modify page content and images. Given the complexity of the site with it ...

updating the name of an HTML element with jQuery

Encountering a problem with setting the class for each li in a group of li tags: function pathContents(fileList) { var $list = $('<ul/>'); $.each(fileList, function (_, file) { $('<li/>').prop('class', &apos ...

Python cannot locate carriage returns (^M or ) that are visible in nano and vi text editors

Currently, I am developing a bash script that generates a log file containing the output of its functions. The issue arises when viewing this log file in Notepad, as it displays a lot of text detailing each step of the process performed by a function. What ...