JavaScript function that returns both a number and a word using regular expressions

Could anyone help me figure out why my code is now returning null when it used to find a match? I want it to search for a match in the string for 1 hour.


var error = "null";

var str = "1 hour"

var strCheck = str.match(/[1]\s[hour]\s/g);

if(String(strCheck) != error) {
alert("It works!");
}

Answer №1

Take a look at this..

var error = "null";

var str = "1 hour "


var strCheck = str.match(/1 hour /g);

if(strCheck != error) {
alert("works!");
}

Explanation:

[] is used to match a single character so [hour] is not correct and if you have change in number of hours you can make it like this:

var error = "null";

var str = "1 hour "


var strCheck = str.match(/[0-9][0-9] hour /g);

if(strCheck != error) {
alert("works!");
}

or Simply use \d to find a digit and \d+ to find one or more digit.
For more see this its simple and clear.

Answer №2

The regular expression pattern [1]\s[hour]\s is not suitable for this task. The character class [] without quantifiers is designed to match only a single character from the specified characters. Therefore, [hour] will match one of the characters - h, o, u, or r. If you want to match the word "hour" as a complete string, a different approach is needed.

To create a more dynamic regex pattern that can even match expressions like "10 hours," the following regex can be used:

/\d+\s*hours?\s*/

Code:

var error = "null";
var str = "1 hour ";
var strCheck = str.match(/\d+\s*hours?\s*/g);
if (strCheck != null) {
  alert("works!");
}

console.log(strCheck);

If the goal is to simply check if the string contains a specific pattern, it's recommended to use RegExp#test instead of String#match.

/\d+\s*hours?\s*/.test(str)

Answer №3

Not sure what type of validation you are looking for using that regex pattern, but this example could be helpful:

\d+\s(hour(s)?)

Explanation:

  • \d+ Represents one or more digits
  • \s Signifies a blank space
  • (hour(s)?) Represents the word hour with an optional letter s at the end for plurality.

The match() method will return an array of results or null if no match is found. My suggestion is to simply check the result as a boolean value instead of comparing it to a "null" string. Your code could look something like this:

var strCheck = str.match(/\d+\s(hour(s)?)/, g);

if (strCheck) {
    alert("It works!");
}

Here are some examples.

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

Add HTML and JavaScript code dynamically with JavaScript

Currently, I am working on a project that involves an HTML table with some basic JS interactions triggered by user clicks. The structure looks something like this: htmlfile.html ... ... position action ...

How to display nested arrays in AngularJs

Within my array contacts[], there are multiple contact objects. Each of these contact objects contain an array labeled hashtags[] consisting of various strings. What is the best way to display these hashtags using ng-repeat? ...

Having trouble getting a NodeJS sample app to start up because it can't locate the 'config' file?

I am currently delving into the world of Node.js and have been attempting to launch a sample application that I recently acquired from a git repository: https://github.com/madhums/node-express-mongoose-demo Despite diligently following all the provided i ...

"Enhance your website with Ajax code that enables automatic refreshing of a PHP file, keeping its values up-to-date

Before diving in, I want to make it clear that my understanding of ajax is limited. I'm currently working on a small application where I have a load.php file that echoes 3 variables: $loadout[0]; $loadout[1]; $loadout[2]; The PHP file is functioning p ...

Error: Supabase and Next.js encountered a self-signed certificate within the certificate chain causing an AuthRetryableFetchError

Encountering an error related to certificates while attempting to retrieve the user from Supabase within getServerSideProps using Next.js: AuthRetryableFetchError: request to https://[redacted].supabase.co/auth/v1/user failed, reason: self signed certifica ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

Ways to define the name and components within the <script setup> scope

Is it possible to define the name and components in a <script setup> mode? In a <script> mode, you can do something like this: export default { name: 'App', props: ['foo', 'greetingMessage'], components: { ...

Vuetify: The checkbox displays the opposite status of whether it is checked or unchecked

Can you help me simplify this problem: In my Vue.js template using Vuetify components, there is a checkbox present: <v-checkbox v-model="selected" label="John" value="John" id ="john" @click.native="checkit"> </v-checkbox> ...

The React application does not appear to update when there are changes made to a child Component

As a beginner in React, I have just started learning how to create a Todo list. Here is what I have so far: However, I am facing an issue where the count of remaining tasks does not update when I check off a task on the list, even though the 'checked ...

What causes the disparity in the functionality of getServerSideProps between index.js and [id].js in NextJS?

Exploring NextJS and React as part of my e-commerce site development journey has been exciting. However, I encountered a roadblock when trying to connect to an external database that requires real-time updates, making getStaticProps unsuitable for my needs ...

expanding the size of a div element on a webpage using jQuery UI

http://jsfiddle.net/nkesh7e0/1/ enter code here I recently experimented with jquery ui resizable and created an example in the provided fiddle link. However, I encountered an issue with the positioning of the anchors. I desire for the anchors to be posi ...

Incorporate data into the div element

I've been attempting to populate a div after selecting 3 different options from select boxes, but nothing seems to be happening. I have confirmed that the PHP function works as expected when tested manually, but I'm unable to get it to populate a ...

Utilizing the doGet approach to send form data upon clicking a button

I am attempting to incorporate a button of type="button" on a form that will process the information using the doGet method instead of doPost for the purpose of updating the URL correctly. Due to this requirement, I am unable to utilize type="submit" or do ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

Tips for toggling password visibility by clicking outside a password field

As I work on creating a password field that allows users to toggle the visibility of their password by clicking an eye icon, I am facing a challenge. I want the password to be hidden automatically when the user clicks outside the field, which requires a co ...

What is the method to retrieve values passed to the next() function in Node.js?

For my current project, I am utilizing Node.js in combination with Express.js to develop the back-end. In middleware functions, next() is commonly used to progress through the chain until reaching the final app.VERB() function. My question is, at what poi ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

Is there a way to eliminate a wrapper object from each element in a JSON array using JavaScript?

My knowledge of JavaScript is limited and I am facing a particular issue. The JSON document at hand looks like this: { "forecast": [ { "day-1": { "forecast_date": "2017-11-23", "morning": { "weather": { " ...

Using Angular Ngrx to Retrieve and Showcase a Selection of Choices from a Java API

When accessing the Java API at localhost://company/products/123/fetchOptions, you can expect a response similar to the following: { "Increase": true, "Decrease" : true, "Like" : true, "Dislike" : true, "Old" : false, "Others" : true } Using Angula ...