A minor problem with the basic regular expression

As a JavaScript novice, I recently delved into the world of regular expressions for the first time.

After attempting to perform some matching operations, I found myself puzzled by the results.

My goal was simple: I wanted to match every website name in the following sentence:

"I go to google.com to search, to facebook.com to share and to yahoo.com to send an email."

This is the code I used:

var text = "I go to google.com to search, to facebook.com to share and to yahoo.com to send an email.";
var pattern = /\w+\.\w+/g;

var matches = pattern.exec(text);

document.write("matches index : " + matches.index + "<br>");
document.write("matches input : " + matches.input + "<br>");
document.write("<br>");
for(i=0 ; i<matches.length ; i++){
    document.write("match number " + i + " : " + matches[i] + "<br>");
}

Here's what I got as a result:

matches index : 0

matches input : i go to google.com to search, to facebook.com to share and to yahoo.com to send an email

match number 0 : google.com

I wondered why it only matched 'google.com' and not the other websites. Can anyone explain?

Answer №1

Quoting the information provided in the MDN documentation:

If your regular expression has the "g" flag enabled, you can make use of the exec method repeatedly to find consecutive matches within the same string. In such cases, the search initiates at the substring of str indicated by the regular expression's lastIndex property (test will similarly progress the lastIndex property).

Hence, execute it multiple times like this:

var match, i = 0;
while(match = pattern.exec(text)) {
    document.write("match number " + (i++) + " : " + match[0] + "<br>");
}

Alternatively, if there are no capture groups, utilize .match():

var matches = text.match(pattern);
for(i=0 ; i<matches.length ; i++){
    document.write("match number " + i + " : " + matches[i] + "<br>");
}

Answer №2

One interesting alternative to iterating through a string is using the replace method, even if no actual replacements are needed.

Consider implementing it like this:

var items = text.replace(pattern,function($0){console.log($0);});

Check out the live demonstration here

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

Slider for comparing images is currently malfunctioning in Firefox

I recently came across a tutorial on how to create an image comparison slider, and it worked flawlessly on Chrome. However, when I tried to load it on Firefox, the slider didn't respond at all. Below is a snippet of the code: const slider = do ...

JavaScript snippet for extracting all gif images from a website's page

I was attempting to retrieve all the images on a webpage and then print them in the console log with the following code: function findImages() { var imgs = document.getElementsByTagName("img"); var imgSrcs = []; for (var i = 0; i < ...

What are the different ways to programmatically change CSS rules using JavaScript in a Firefox Add-on, leveraging XUL, SDK, or WebExtensions methods?

Looking to dynamically alter a CSS rule set through JavaScript within a Firefox Add-on using XUL, SDK or WebExtensions techniques. Specifically targeting support for Firefox versions 29.0b1 through 49.0a1. The main issue I want to address is modifying the ...

Error message encountered in Express.js when trying to apply the ejs function: "View is not a constructor"

I am attempting to execute certain tasks before the original app.get function is called. After referring to this page, I applied their method which worked for the most part, except when using a rendering engine. The code snippet below demonstrates what I ...

Tips for positioning the Google Custom Search bar

I am looking to position the Google custom search box on the left side of my website. Currently, I am using a website builder called imxprs and have implemented this code for my custom search box. <script> (function() { var cx = '013012 ...

What effect does setting AutoPostBack to "true" in an ASP dropdownlist have on the fireEvent() function?

I am currently working on an aspx page. This page includes three dropdown lists and a button, all of which are populated dynamically based on the code written in the code-behind file (.cs file). To achieve this, I need to utilize two event handler methods ...

Error in Layout of Navigation Panel and Tabbed Pages

Working on a school project, I encountered a challenge. I found two useful solutions from the W3 website - a sticky navigation bar and the ability to include tabs on a single page for a cleaner presentation of information. However, when trying to implement ...

Unable to display elements from an array in the dropdown menu generated by v-for

Having just started learning Vue.js, I am facing a challenge in rendering the following array: countries: ["US", "UK", "EU" ] I want to display this array in a select menu: <select> <option disabled value="">Your Country</option& ...

php reload page with included content

I am currently in the process of building a website using php, jquery, Sass, Bootstrap, and more. The setup I have in place involves one main index page that contains all the necessary includes for the header, CSS files, and JavaScript files. Different pa ...

Array's Javascript length of 0

I have encountered some strange behavior with the following code. It's displaying an array length of 0 even though I can see a length greater than 0 when printing it right before that: var getTopSelection = function(callback) { var topSelection = ...

Reducing the slide margins in impress.js?

When using Impress.js, I noticed that the default slides have a large left margin (or padding - it's hard to determine with Firefox's Inspector). I have a slide with a wide <pre> block that would fit if it were aligned to the left, but it d ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

The SQL query fails to execute when triggered by window.location.href

Whenever a selection is made, I trigger a Javascript code using the onchange function. I pass along 2 parameters: //capaciteit.php function testfunction(week, id) { window.location.href = "capaciteitberekening.php?week=" + week + "&id=" + id; } The f ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

Error when trying to parse JSON due to an invalid character

I am facing a challenge while trying to parse JSON data from an external json file, which is in the form of an Array. Unfortunately, no data is being returned and I encountered an error (F12) stating 'Invalid character'. What could be causing thi ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

What are the strategies for finding elements within multiple layers of shadow DOM?

I am struggling to find the Xpath or CSS Selector for the JSON download button on this particular page. Although I attempted to copy the selector using Chrome browser, it doesn't seem to locate the button when I try to find it using control find. Xp ...

Exploring the concept of multiple inheritance using ES6 classes

My research on this topic has been primarily focused on BabelJS and MDN. However, I acknowledge that there may be more information out there regarding the ES6 Spec that I have not yet explored. I am curious about whether ES6 supports multiple inheritance ...

Obtaining distinct values from a column by using regular expressions to filter in SQL

Currently, I am working with a table in which I execute a query to retrieve one column that matches a specific regular expression, (\/.+\/\?). The content of the resulting column looks like this: /Anything here/? For example: \abc&b ...

"Utilizing Bootstrap to create a multiselect feature that can dynamically

I am facing an issue with receiving alerts for dynamically added bootstrap select elements <html> <head> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link hr ...