Ensuring an equal count of vowels and consonants through Regex validation

Could someone please provide guidance on how I can perform Regex form validation in JavaScript?

The student's name must consist of only alphabet characters, with an equal number of vowels and consonants.

Answer №1

Using Regex alone might not be sufficient for this task.

In my approach, I filter out all non-vowel characters in a string and calculate their length, as well as the length of consonants. To validate the name, we compare the number of vowels and consonants.

const getNumberOfVowels = (string) => string.replace(/[^aeiouAEIOU]/g, "").length;
const getNumberOfConsonants = (string) => string.replace(/[aeiouAEIOU]/g, "").length;

const isAValidName = (name) => {
  const vowels = getNumberOfVowels(name);
  const consonants = getNumberOfConsonants(name);

  return vowels === consonants;
}

console.log(isAValidName("Adam"));

Answer №2

To accomplish this task, you must develop a function that serves two purposes:

  1. Verify if all characters are alphabetic
  2. Contrast the quantity of vowels with consonants

The expressions required for this purpose include:

  • /^[a-z]+$/i – Solely alphabetical characters (regardless of case)
  • /[aeiouy]/ig – Only vowels
  • /[^aeiouy]/ig– Only consonants

const isValidName = (name) =>
  /^[a-z]+$/i.test(name) &&
  name.match(/[aeiouy]/ig).length === name.match(/[^aeiouy]/ig).length;

console.log(isValidName('Gene'));    // Valid
console.log(isValidName('Abby'));    // Valid
console.log(isValidName('Charles')); // Invalid

Answer №3

To ensure the validity of a student's name, you can utilize the following code snippet:

const validateStudentName = (name) => {
  const regExp = /[^a-zA-Z]/;
  const isEven = name.length % 2 == 0;
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  const vowelCount = [...name].reduce((sum, char) => vowels.includes(char.toLowerCase()) ? sum + 1 : sum, 0);
  console.log(!regExp.test(name) && isEven && vowelCount === name.length / 2);
}

validateStudentName("abaci");

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 $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: https://i.sstatic.net/ws ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

Access the web location using jQuery's ajax functionality

I need help figuring out how to post data to my "mail.py" script without knowing the URL link. Both my jQuery AJAX code and JavaScript file are located in RKProjects/scripts_js/contactform.js The Python script I want to connect to is stored in RKProjects ...

In AngularJS, I was attempting to display array indexes in reverse order. Can anyone provide guidance on how to achieve this?

<tr ng-repeat="qualityalert in qualityalerts" current="$parent.start;$parent.start=$parent.start+(qualityalerts.length);"> <td class="v-middle">{{current + $index}}</td> </tr> Important: I was talking about this specific code snipp ...

Is it not possible to update the innerHTML stored in a variable in real-time?

I am attempting to link a div's text with a variable that changes its value based on different button clicks (using plain JavaScript), but I am struggling to update the inner HTML dynamically. It only displays the initial value set on page load. What ...

Error encountered in jQuery validation script due to incorrect data type

Looking to experiment with the jQuery validate plugin in an MVC application by trying a simple example. Here is a JS module with a method: ValidateRestriction: function (element) { var inputs = $('form').validator(); inputs.data("validat ...

Ways to reference an Array variable using a string in JavaScript

const EleList = [1,2,3] name = 'Ele' const render = function(type){ window[type + 'List'].forEach(function(value){ console.log("LOL") }); render('Ele') I'm trying to dynamically call an array using a string. Wh ...

Cross-browser compatible (Chrome, Internet Explorer, Firefox)

I'm having trouble understanding why this script is not functioning correctly in Internet Explorer, although it works fine in Firefox and Chrome. Whenever I attempt to run the script in IE, I receive an error message stating "ACTIVEX stop script". An ...

An error occurs with Three JS when trying to access a S3 Bucket used as a CDN due to Cross Origin

function displayItem() { startScene(); THREE.ImageUtils.crossOrigin = "anonymous"; var mtlLoader = new THREE.MTLLoader(); mtlLoader.setTexturePath('https://cdn.rubyrealms.com/textures/'); mtlLoader.setPath('https://cdn.ru ...

Utilize the information from the first page in order to enhance the content on

I have developed a straightforward app that opens a new page displaying the text of the list element clicked by the user. My goal is to pass the device variable to a page named deviceDetails. <ion-list> <ion-item *ngFor="let device of devices" ...

Using jQuery.ajax() to capture and log the details of an HTTP request

I have a function that makes an HTTP POST request and I would like to log it for debugging purposes. Here is the code: function sendPostRequest(URL, DATA, callback) { $.ajax({ url: URL, type: "POST", dataType: "text", c ...

Starting multiple timers in sequence using jQuery

I'm working on this code snippet var duration = 60 * $(".duration").val(), display = $(".timer"); startTimer(duration, display); function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

Is the existence of the file also verified by JavaScript's realpathSync() function?

I want to utilize node.js FileSystem realpathSync() to find the actual path of a file. Does realpathSync() also verify if the file exists? Would this code be sufficient: try { res = fs.realpathSync(path); } catch (err) { ...

Refreshing browser data with JQuery ajax when the browser is refreshed

Is there a way in JavaScript or jQuery to stop the page from refreshing (F5) and only update certain parts of the page using Ajax? I attempted the following code, but it did not work: $(window).bind('beforeunload', function(event) { ...

Executing a Node.js HTTP GET request is a breeze

I've encountered an issue while attempting to send an HTTP GET request using Node.js. The request to '/path/to/file?query=string' has failed with the error message: read ECONNRESET Any suggestions on how I can resolve this problem? Thank ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

Transferring information from a template to a view within Django

I am currently in the process of creating a bus reservation platform using Django. When a user searches for buses on a specific route, a list of available buses is displayed. Each bus in the list has a 'book' button that redirects to a new page c ...

The Flask web API is unable to process image files sent through AJAX requests

My Flask API is quite basic and it interacts with a DNN model. The Python backend code looks something like this: from flask import request from flask import jsonify from flask import Flask import io app = Flask(__name__) @app.route("/predict" ...