What is the best way to divide a string by identifying a specific character that comes after another character?

I have a string in the format:

"MyGroup/exercise#324242-BC2_asd213"

How can I extract the portion of the string before -? Specifically, I want to retrieve MyGroup/exercise#324242. It is important to note that the split should occur after the first instance of - following the #, as there may be other instances of - within the string.

"MyTeam/running-marathon#789098"

In this example, the desired output would be MyTeam/running-marathon#567657

My current method:

.substring(0, vfi.lastIndexOf("-"));

However, I am exploring alternative approaches that are anchor with the "#" symbol for greater precision.

Answer №1

To achieve this, you can implement a regular expression:

const regex = /^([^#]+[^-]*).*$/;

function getSubstringBetweenHashAndDash(value: string) {
  return value.replace(regex, '$1');
}
  • ^ indicates the beginning of the string
  • [^#]+ will match one or more characters that are not #
  • [^-]* will match zero or more characters other than -
  • .* will match any character zero or more times
  • $ denotes the end of the string

The parentheses capture the desired match so that it can be used for replacement (using $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

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

Can defaults be set for interface function parameters in TypeScript?

Expanding on the Number class: interface Number { evolution(now: number, before: number): string; } Number.prototype.magnitude = function(d=1, suffix="") { //… } I enjoy incorporating default parameters. However, encountering an issue when l ...

Transferring data between components in React by passing parameters through Links

When calling another component like <A x={y}/>, we can then access props.x inside component A. However, in the case of calling EditCertificate, the id needs to be passed to the component. I am using a Link here and struggling to pass the id successf ...

Create a new data structure that generates a different type of generic data

I'm struggling to find the right words, so I'll provide an illustration: // For observables type UnwrappedObs<T> = T extends Observable<infer T> ? T : never; // For promises type UnwrappedPro<T> = T extends PromiseLike<infer ...

This code cannot be called as a function, Every individual in the union

My approach has been aligned with the current architecture, focusing on reducing complexity as much as possible. I have strived for the best possible outcome, but encountered a single failed test along the way. After three days of struggling, I'm cl ...

PHP split the string into segments using capital letters

One example is the string: "iCanSeeBluePeople". It needs to be separated into an array by capital letters, with the first word starting in lowercase. The desired output would be an array like ["i","Can","See","Blue","People"] The strings could take variou ...

Rollup is encountering challenges with handling dependencies that are TypeScript files, resulting in an error being thrown: "Unexpected token."

Check out this GitHub repository for a sample project that showcases the issue. Here is the content of my package.json: { "name": "rollup-ts-deps", "version": "1.0.0", "description": "", ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

What strategies can be used to prevent redundancy when defining strings in both type declarations and type guards?

I have encountered duplication in my code where allowed strings are declared twice, once in the type declaration and again in the type guard. How can I refactor my code to eliminate this redundancy? // inspired by: https://github.com/mattdesl/parse-unit ...

Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: http ...

Similar to the getState() function in react-redux, ngrx provides a similar method in Angular 6 with ngrx 6

Recently, I developed an application with react and redux where I used the getState() method to retrieve the state of the store and extract a specific slice using destructuring. Here's an example: const { user } = getState(); Now, I am transitioning ...

complete() method is not triggered by Observable

Note: I understand that there is a timer observable from rxjs, but for the purpose of this project, I am using it as a proof of concept to enhance my understanding of observables. In my Angular application, I have developed a timer with a start button, a ...

Sorting JSON arrays in Typescript or Angular with a custom order

Is there a way to properly sort a JSON array in Angular? Here is the array for reference: {"title":"DEASDFS","Id":11}, {"title":"AASDBSC","Id":2}, {"title":"JDADKL","Id":6}, {"title":"MDASDNO","Id":3}, {"title":"GHFASDI","Id":15}, {"title":"HASDFAI","Id": ...

Is there a way to configure tsconfig so that it can properly recognize ".graphql" files and aliases when they are imported into components?

Currently, I have encountered an issue where including "graphql" files in my components is leading to TypeScript errors due to unrecognized import pathing. Despite the error, the functionality works as expected. import QUERY_GET_CATS from "@gql/GetCats.gra ...

Following an update from typescript version 2.3.4 to 2.4.2, I encountered a compilation error stating, "The type definition file for 'reflect-metadata' cannot be found."

Recently, I encountered an issue with my React / Mobex application written in TypeScript and built by Webpack 1. Upon updating the TypeScript version from 2.3.4 to 2.4.2, an error started occurring. The error message reads: ERROR in C:\myproject&bsol ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

ESlint is unable to parse typescript in .vue files

After using vue ui to build my project, here is the content of my package.json: "@vue/cli-plugin-eslint": "^4.1.0", "@vue/cli-plugin-typescript": "^4.1.0", "@vue/eslint-config-standard": "^4.0.0", "@vue/eslint-config-typescript": "^4.0.0", "eslint": "^5.1 ...

In Angular 2, the routerLink feature appears as regular text on the screen

Recently, I encountered an issue with routerLink in my Angular 2 project. I am currently using Visual Studio 2015 to develop a Single Page Application with routing functionality. However, I noticed that when I click on an anchor tag with [routerLink], it d ...

Continue accepting input from the user until the period symbol "." is encountered

I'm facing a challenge in implementing a specific section of my code. The task at hand is to capture a string input from the user, which can be up to 256 characters long. The input should preserve any spacing and newlines as entered by the user. When ...

Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes method ...