Is there a shared instance for regular expressions created using expression literals?

In the book "Javascript: The Good Parts" by Crockford, there is a code snippet that highlights how RegExp objects created using regular expression literals share a single instance:

function create_matcher() {
    return /a/gi;
}

var x = create_matcher();
var y = create_matcher();

// Caution: x and y are referencing the same object!

x.lastIndex = 10;

document.writeln(y.lastIndex); // Output: 10

Question: Does this behavior apply to other types of literals as well? I tried adapting the code above to use the string "string", but encountered multiple errors.

Answer №1

It's important to note that regular expression literals are not shared. According to the specification on Regular Expression Literals:

A regular expression literal is an input element that is converted to a RegExp object (see 15.10) each time the literal is evaluated. This means that even if two regular expression literals have identical content, they will never compare as === to each other.

With the introduction of ES5, there was a change in how this behavior worked. Check out what Old ECMAScript 3 had to say about it:

In ECMAScript 3, a regular expression literal is converted to a RegExp object (section 15.10) when it is scanned. The object is created before the containing program or function begins evaluation. Each literal produces a reference to this single object without creating new ones. Even with identical contents, two regular expression literals in a program will not be comparable using ===.

While this approach aimed at sharing compilation results of the regex engine across evaluations, it actually led to some issues, as seen in certain buggy programs.

If you're relying on outdated information, it might be time to consider upgrading to a newer edition of your resources.

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 white-spaces in Quill JS do not retain their original formatting

I recently integrated Quill JS editor into my website. During testing, I noticed that any text inputted after a white space gets emitted when alerting the content. Below is the HTML code snippet: <div id="postCommentEditor" class="postCo ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

Node Express application experiences issues with Handlebars rendering additional empty objects from JSON arrays

Currently, I am attempting to retrieve data from a REST API call and display it as a list using Handlebars, which functions as my view engine in a Node Express App. Below is the route I am using: router.get('api/projects', function(req, res){ ...

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" Attempting to achieve this ...

What is the best method for accessing the service response data when I am sending back an array of custom map with a promise as an object?

Sharing my code snippet below: function createObject(title, array){ this.title = title; this.array = array; } //$scope.objects is an array of objects function mapPromise(title, promise){ this.title= title; this.promise = promise; }; var fet ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

Titanium: Warning upon initiation

Is it feasible to trigger an alert immediately after a window finishes loading? I am using a create window function followed by an alert message, then returning. function NewView() { var self = Ti.UI.createWindow({}); alert("A basic or confirm al ...

"click on the delete button and then hit the addButton

I have created a website where users can save and delete work hours. I am facing an issue where I can save the hours at the beginning, but once I delete them, I cannot save anything anymore. Additionally, when I reload the page, the deleted data reappears. ...

Issues with refreshing Datatables functionality

I’ve hit a roadblock while troubleshooting this issue, and it’s gotten quite frustrating. That's why I've turned to Stackoverflow for help once again. As a beginner, I ask for your patience and thank you in advance for any assistance. In my ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...

Create a customizable Tree structure that includes checkboxes for each item and features drag

I am currently working on incorporating a Tree view with checkboxes and drag & drop functionality in Vue. However, I am unsure of where to begin. While I have successfully implemented checkboxes, I am struggling to figure out how to enable the feature whe ...

Combining Laravel with React

Currently in the process of developing a substantial real estate listings platform with react and laravel. Can you suggest which approach would be better for this project and explain why? Option 1: Implement laravel react presets and store all react compo ...

Avoid reloading the page in PHP when the browser back button is clicked

I've built an HTML form where the values are passed to a second page using POST method. On the second page, I have an edit button that, when clicked, redirects back to the HTML form page with the user's typed values. However, my dilemma is figuri ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

Querying with regular expressions in MongoDB: a comprehensive guide

I'm facing an issue and need some help: {"_id":ObjectId("XXXXXXXX"),"phone":"123456"} My goal is to query a document where the phone field length is 5. I tried running the following command, db.Phone.find({"phone":{"$regex":"\d{5}"}}) or db ...

"Efficient Querying with MYSQL XDEVAPI Through Multiple OR (II) Requests

Currently, I am utilizing the XDEVAPI and attempting to incorporate the or(||) statement in JavaScript. However, it appears to malfunction after 1 or/(||) statements have been included. I need to fetch data from the database based on 5 distinct statuses: . ...

Calculating the mean value of a multidimensional array that has been sorted in JavaScript

Check out the structure of my JSON File below. { "questions": ["Question1", "Question2"], "orgs": ["Org1", "Org2", "Org3"], "dates": ["Q1", "Q2", "Q3"], "values": [ [ [5, 88, 18], [50, 83, 10], ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Mastering the Art of Leveraging Conditionals in JavaScript's Find Function

I'm curious about the implementation of an if statement in the JavaScript find function. My objective is to add the class "filtered-out" to the elements in my cars array when their values do not match. cars.map(car => active_filters.find(x => ...