Checking if a string in Typescript contains vowels using Regex

Is there anyone who can assist me with creating a regex to check if a string contains vowels?

EX : Hi Team // True
     H // False

I have tried using the following regex but it's not giving me the desired outcome.

[aeiou]

Answer №1

Here's an example to detect vowels

const withVowels = 'This is a sentence with vowels';
const withoutVowels = 'dfjgbvcnr tkhlgj bdhs'; // No vowels here

const hasVowelsRegex = /[aeiouy]/g; 

console.log(!!withVowels.match(hasVowelsRegex));
console.log(!!withoutVowels.match(hasVowelsRegex));

Answer №2

Take a look at this.

const regex = /^[aeiouy]+$/gmi;
const str = `aeyiuo
aeYYuo
qrcbk
aeeeee
normal
Text
extTT`;
let m;

while ((m = regex.exec(str)) !== null) {
    // To prevent infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // Access the result using the `m` variable
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

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

Tips for reusing a Jest mock for react-router's useHistory

When testing my code, I set up a mock for the useHistory hook from react-router-dom like this: jest.mock("react-router-dom", () => ({ useHistory: () => ({ length: 13, push: jest.fn(), block: jest.fn(), createHref: jest.fn(), go ...

Sequelize is not giving the expected model even after utilizing `include: [{ model: this.buildModel, required: true }]`

I've hit a roadblock trying to solve this problem. Despite my belief that I've correctly handled the migration, model definition, and query, I'm unable to retrieve the build in my iteration. Below are the models: SequelizeBuildModel.ts @Ta ...

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

Angular Throws 'Expression Changed After Check' Error When Behavior Subject is Triggered

In my Angular 11 project, I am utilizing a BehaviorSubject to update the toolbar content from various components. The toolbar subscribes to the BehaviorSubject in the following manner: <breadcrumbs [crumbs]="messageService.getBreadcrumbs() | async& ...

TS2307 Error: The specified module (external, private module) could not be located

I have come across similar queries, such as tsc throws `TS2307: Cannot find module` for a local file . In my case, I am dealing with a private external module hosted on a local git server and successfully including it in my application. PhpStorm is able ...

Exploring the world of Angular and utilizing TFS for seamless

Embarking on a new Angular development journey, I have relied on Angular documentation to guide me through the process - from installing node packages to creating a new Angular project. However, I am now looking to integrate my development work into an ex ...

Is it possible to export all types/interfaces from .d.ts files within multiple folders using index.ts in a React TypeScript project?

In my current React project, I am managing multiple configuration folders: -config -api/ |index.ts |types.d.ts -routes/ |index.ts |types.d.ts ... For example, in the api/index.ts file, I can import necessary types using import {SomeTyp ...

Utilizing TypedPropertyDescriptor to limit decorators in Typescript when using decorator factories

When it comes to restricting what a decorator can apply on, the standard method involves using a TypedPropertyDescriptor like so: export function decorator(target, key, TypedPropertyDescriptor<T extends ...>) {...} While this approach works well whe ...

Can NgZone be utilized within a shared service instance?

I am currently working on creating an injectable singleton service for my application that will provide all components with information about the window width and height, as well as notify them when the page is scrolled or resized. Below is the code snipp ...

Jest: A guide on mocking esModule methods

In my code, I have a function that utilizes the library jszip to zip folders and files: // app.ts const runJszip = async (): Promise<void> => { const zip = new Jszip(); zip.folder('folder')?.file('file.txt', 'just som ...

Is there a way to make the parent elements invisible when there are no child elements present?

Take this scenario for instance: <ul *ngIf="hasAnyPermission(['A:READ', 'B:READ', ...])"> <li *ngIf="hayPermission('A:READ')"> a </li> <li *ngIf="hasPermission('B:RE ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

Inversify: class-based contextual dependency injection

I am currently experimenting with injecting loggers into various classes using inversify. My goal is to pass the target class name to the logger for categorization. The challenge I'm facing is the inability to access the target name from where I am c ...

What is the best approach to converting an array of strings into a TypeScript type map with keys corresponding to specific types?

The code provided below is currently working without any type errors: type Events = { SOME_EVENT: number; OTHER_EVENT: string } interface EventEmitter<EventTypes> { on<K extends keyof EventTypes>(s: K, listener: (v: EventTypes[K]) => voi ...

WebStorm is unable to detect tsconfig paths

Currently, we are facing an issue with WebStorm identifying some of our named paths as problematic. Despite this, everything compiles correctly with webpack. Here is how our project is structured: apps app1 tsconfig.e2e.json src tests ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...

Separate the string by commas, excluding any commas that are within quotation marks - javascript

While similar questions have been asked in this forum before, my specific requirement differs slightly. Apologies if this causes any confusion. The string I am working with is as follows - myString = " "123","ABC", "ABC,DEF", "GHI" " My goal is to spli ...

Integrity parameter in Angular2+ is utilized for ensuring the integrity of a local script file

I have encountered an issue with my AngularJS project. I have 2 scripts located in the asset folder and I generated integrity hashes for them using . While everything works fine on my localhost, when I upload it to the server, only Internet Explorer seems ...

Understanding the process of retrieving form data files sent from Angular to TYPO3/PHP via a Post request

I've been working on uploading an image from Angular to the TYPO3 backend, but I'm struggling to read the request body in the Controller. Here's the code snippet from my Angular side: HTML: <input multiple type="file" (change ...

Error: The method that was custom created is not functioning as expected

I am working on a project where I have a collection of hero buttons that come with a customized animation which is defined in the button.component.ts file. These buttons start off as inactive, but when one is clicked, it should become active. To achieve th ...