The regular expression pattern ((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,} is functional when used on regexpal.com, however, it does not yield the

Within the code snippet below, the regular expression in the "pattern" variable is specifically designed to only match the criteria mentioned in the comment (which requires a minimum of 1 letter followed by a dot, and then two letters).

var link = "Help"
// matches www-data.it -- needs at least (1 letter + '.' + 2 letters )
var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}';
var re2 = new RegExp('^' + pattern, 'i');

// if no http and there is something.something
if (link.search(re2) == 0)
{
    link = link;
}

Testing this code on shows successful results as expected, where only strings with the format something.something pass.

However, testing it on JSFiddle and in live production results in unexpected matches such as "Help." http://jsfiddle.net/2jU4D/

This discrepancy raises questions about the functionality of the code. What could be causing this inconsistency?

Answer №1

For creating the regular expression, it is recommended to use native regex syntax:

var re2 = /^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}/i;

When constructing the regular expression, keep in mind that the \. will appear as just a period . when using new RegExp(). The backslash serves as an escape character in string grammar and may be ignored during initial parsing as a string.

Another approach could be:

var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}';
var re2 = new RegExp('^' + pattern, 'i');

To ensure the correct string is passed to the RegExp constructor, doubling the backslash is necessary.

Answer №2

Below is the analysis of what it corresponds to. I suggest replacing all capture groups with non-capture groups and placing all anchors within the body of a regex (instead of appending them later).

The regex appears to be valid, although there may be some issues with the delimiters or how it is being utilized.
Take note of the necessary components, as there seems to be an issue with the matching process, however, this might not necessarily be due to the regex itself.

(                         # (1 start)
    ( xn-- )?                 # (2), optional capture 'xn--'
    [a-z0-9]+                 # multiple occurrences of lower case letters or digits
    ( - [a-z0-9]+ )*          # (3), optional multiple captures of '-' followed by lower case letters or digits
    \.                        # a dot '.'
)+                        # (1 end), repeat this pattern multiple times
[a-z]{2,}                 # Two or more lower case letters

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

Run a function continuously while a key is being held down

I am currently working on a Javascript program that will move a div up and down based on key inputs. The idea is to continuously update the 'top' style value of the div while a specific key is pressed. While the basic function works, I am struggl ...

Leverage all the documents obtained from a collection to reference in a Vue component

I am attempting to display all documents from a Firestore collection in a table using refs, but I am unsure about accessing each field for template ref. getDocs(collection(db, "usr")) .then((querySnapshot) => { querySnapshot.forEach((doc ...

Express server is receiving undefined post parameters from Axios in Vue, even though they are clearly defined in Vue

Within my code, I am utilizing an <img> element as shown below: <img v-bind:word = "thing" @click="action" align="center" src="../assets/pic.png"/> Alongside, there is a method structured in this manner: ...

Creating a compact Swiper slider: reducing image size without sacrificing full window coverage!

Utilizing Swiper to craft a slider that occupies the entire window, with a slight margin for a bar-- no issues there. (https://i.sstatic.net/qcGBA.jpg) However, the image I placed in for the slide () appears to be excessively enlarged. Is there a way to ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

Connecting event listeners to offspring elements, the main element, and the entire document

My request is as follows: I have multiple boxes displayed on a webpage, each containing clickable divs and text. When a user clicks on a clickable div, an alert should appear confirming the click. Clicking on the text itself should not trigger any action. ...

What is the best way to switch the visibility of a div on click from another div?

My goal is to make a div toggle visible or hidden when another div is clicked. The only connection between the two divs is that they are both nested within the same parent div. There's a DIV element with the class of "comment" which contains a DIV ele ...

Tips for effectively parsing extensive nested JSON structures?

JSON Data on PasteBin I need assistance in converting this JSON data into an Object. It seems valid according to jsonlint, but I'm encountering issues with parsing it. Any help would be greatly appreciated. "Data":[{...},{...},] // structured like t ...

Trigger the opening of a bootstrap modal from an external source on the current page

One common question is how to load a modal from another page onto the current page, or how to open a modal on the current page when it loads. My idea is a little different: I want to click on an image hotspot (like a person in a team photo) on the /home p ...

Looking for assistance with importing OBJ and MTL files into Three.js?

I'm encountering a strange issue while attempting to load an OBJ and MTL file in Three.js using the OBJMTLLoader() function and am unable to find a solution online. My project structure includes an index.html file and a js folder with all the necessar ...

Is there a way to conceal the headers during an ajax request?

I'm currently exploring APIs using jQuery and Ajax. To set the header of Ajax, I typically use code similar to this: headers: { "My-First-Header":"first value", "My-Second-Header":"second value" }, I am working on a basic school project and ...

Unable to assign a className to a personalized React component - troubleshooting needed!

I have a component that relies on another component. I am trying to pass CSS positioning from the outer component to the inner one by using the following code: import OptionsMenu from './OptionsMenu' import { withStyles } from 'material-ui/ ...

Transferring JSON data using AJAX

I am having trouble sending JSON via AJAX using pure JavaScript. While I can successfully retrieve values back from PHP, I am struggling to retrieve a specific JSON array. var mname = ["john", "mary", "eva"]; var fname = 678; clicked_keyword_test = {"last ...

What could be causing the res.sendfile() method to fail when invoked through a jQuery ajax call?

Problem: The first ajax call in the main.js is functioning correctly, but there seems to be an issue with the second one. Although it appears to be working initially, I suspect that there may be a bug present. Upon clicking the button, I am able to access ...

There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { i ...

Having difficulties with Vue components displaying in Laravel's blade.php file

Let me share my current setup with you: This is the main "Welcome.blade.php" file where I have included relevant information as the file is quite lengthy: <div id='app'> <router-view></router-view> </div> <script src ...

What could be causing ng-repeat to malfunction?

My ng-repeat is not working with the table - only the header part is being displayed in the output. I have checked my binding and it seems to be correct, but I know I am missing something. Can someone please help me figure out what I am doing wrong? JAVA ...

When using express, the response.sendFile() function is causing an Uncaught SyntaxError with the error message: Unexpected token <

Currently, I'm utilizing react-router with browserHistory. There is a specific function in my code that is meant to send the Index.html file since the routing is handled client-side with react-router. However, there seems to be an issue where the serv ...

Issue with Google Script not initializing in a second form

I'm currently working on a project that is bound to a Google Sheet container. The purpose of this project is to search for a specific value in one column, and based on the result, either mark the record as complete, allow for missing values to be fill ...

The Facebook SDK's function appears to be triggering twice

I am currently in the process of integrating a Facebook login button into my website and have made progress, but I have encountered a problem. The Facebook SDK JavaScript code that I am using is as follows: function statusChangeCallback(response) { ...