Extract specific text from a string using TypeScript

I have a specific text format that goes like this:

test/something

The test/ part always remains the same, but the word following it varies. I am trying to extract the word after test/, which is essentially what I need. Sometimes, this pattern appears within a sentence, such as:

Please grab the word after test/something thank you
.

In this scenario, I only want to capture something, not the additional words like thank you.

I came up with this code:

const start = text.indexOf('test/');
const end = text.substring(start).indexOf(' ') + start;
const result = text.substring(start, end).replace('test/', '');

This solution works when the pattern is surrounded by spaces in a sentence. How can I modify it to handle all cases, even if the input string consists solely of test/something without any other characters before or after it?

Answer №1

Instead of using a regular expression, I would suggest utilizing a different approach. Start by locating the string "test/", then capture everything that is not a space following it and retrieve this captured group.

const text = 'Please grab the word after test/something thank you';
const word = text.match(/test\/(\S+)/)?.[1];
console.log(word);

If you are working in a modern environment, there is an easier way to find the word following "test/" without the need for capturing groups.

const text = 'Please grab the word after test/something thank you';
const word = text.match(/(?<=test\/)\S+/)?.[0];
console.log(word);

Answer №2

To achieve the desired outcome, you can utilize a regular expression that employs a positive lookbehind ((?<=...)). This regex will capture non-greedily anything (.+?) up to the first word boundary (\b):

const extract = (s) => s.match(/(?<=test\/).+?\b/);

console.log(extract('test/something'));
console.log(extract('Kindly fetch the word following test/something. Thank you.'));

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

Discovering the frequency of a specific key in a JSON object or array using JavaScript

Suppose I have a JSON object with the given data, how can I determine the frequency of the key: "StateID"? [{"StateID":"42","State_name":"Badakhshan","CountryID":"1"}, {"StateID":"43","State_name":"Badgis","CountryID":"1"}, {"StateID":"44","State_name": ...

The script for tracking cursor coordinates is incompatible with other JavaScript code

<html> <script language="javascript"> document.onmousemove=function(evt) { evt = (evt || event); document.getElementById('x').value = evt.clientX; document.getElementById('y').value = evt.clientY; document.ge ...

Utilizing jQuery's Ajax functionality to extract filtered data from mySQL

I've been working on sending query strings fetched by clicking radio buttons to the server in order to receive a response in XML format. Although I'm close to finding a solution, I'm struggling to debug why it's not functioning as expec ...

In jQuery, utilizing dynamic class names with variables

I have a series of images with unique classes such as: .1a .2a .3a .4a ..... I am looking to toggle some other classes named .1b .2b .3b .. and so on so that: '.1a' toggles to '1b' '.2a' toggles to &ap ...

Validating Whether a Given String is a Globally Unique Identifier

Is there a reliable way to differentiate between a GUID and a string of numbers? Must a GUID always include at least one alphabetic character? ...

utilizing a fresh item as an argument in javascript

I'm encountering an issue with a simple one-line function. The function takes an argument as an object and assigns a value to that object, but when I try to alert the value, it shows up as undefined. Can anyone help me identify what's causing thi ...

Step-by-step guide for properly transferring PHP MySQL data to ChartJs

I am looking to create bar charts and pie charts using ChartJs, with data fetched from php and mysql. Specifically, I want to generate a bar chart that illustrates the statistics of male and female students, along with the total number of students. The des ...

What is the best method for performing a color-specific hit test on a specific image within a webpage?

I want a way to detect when my mouse hovers over a specific image and changes color upon hovering over it. Is there a way to achieve this and what steps should I follow? ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

The function ensure_csrf_token is failing to set the CSRF cookie in the cookies section

I am facing an issue with setting up a CSRF token in my application. Firstly, I have a simple generic view in Python: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, ...

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

Guide on Creating a Smooth jQuery Scroll Animation from Top to Bottom and Bottom to Top for a Landing Page Navigation Menu

I'm in the process of developing a landing page website where my navigation links smoothly scroll to different sections on the page. Currently, when I click on a nav link, it instantly takes me to the bottom and then back to the top. However, I want t ...

Looking for the location of a matching brace in a dataset?

As a newbie in the world of coding, I have embarked on learning about NodeJs file system module. Currently, my focus is on handling a large data file stored as a string. The challenge that I am facing is with locating the matching close brace and its pos ...

A guide on setting up ExpressJS Error Handling to display custom error messages based on the corresponding HTTP Status codes

I am struggling to figure out how to implement this task. You need to create an error on the /error path and pass it to the next function. Make sure to use appropriate error status codes for displaying different types of error messages. I attempted using ...

An error occurred stating 'TypeError: jsdom.jsdom is not a function' while using the paper-node.js in the npm paper module

Recently, I added the webppl-agents library to my project, including webppl and webppl-dp. However, when attempting to execute the command line test, I encountered some difficulties. It seems that there is a dependency problem with jsdom from the npm paper ...

What causes the collapse of the React Bootstrap Navbar?

While going through the React-Bootstrap documentation, I stumbled upon this code snippet which I used to create my navbar -> However, after clearing the session on Google Chrome, my navbar remained collapsed. https://i.sstatic.net/B67mN.png I tried s ...

The term "Cardlist" has not been defined and is therefore causing an

I created a CardList and attempted to add cards into the list using map, but encountered an error import React from 'react'; import Card from './Card'; const CardsContainer = ({robots}) => { const cardComponents = robots.map((r ...

The .angular-cli.json file is causing issues with loading scripts

I have recently updated my .angular-cli.json file by adding new scripts in the following format: "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html ...

Ways to analyze users who have clicked a button

After a user registers, they are automatically taken to /proto where they can view a list of animals available for adoption. However, the challenge lies in identifying the specific user who clicked the button (as this information must be associated with th ...

Unable to designate decimal value as the default in DropdownListFor in ASP.NET Core when utilizing JavaScript

Everything appears to be functioning properly, except when dealing with decimal values in the following code snippet: $('select#listspec_0__qty option[value = 105.3]').attr("selected", true); ...