What is the best way to create a Regex that specifically targets the initial match in every line?

Looking for a way to efficiently copy a long list of properties without their assignments being included? Avoid retyping by using a regular expression in VSCode.

Check out this sample TypeScript code snippet:

    this.anchorBillingAddress = this.page.getByTestId('billing-address-section');
    this.anchorShippingAddress = this.page.getByTestId('shipping-address-section');
    this.anchorBilling = this.page.getByTestId('billing-section');
    this.anchorGeneral = this.page.getByTestId('general-section');
    this.anchorStatistics = this.page.getByTestId('statistics-section');

The desired output:

this.anchorBillingAddress

this.anchorShippingAddress

this.anchorBilling

this.anchorGeneral

this.anchorStatistics

Attempted solution using this[^\s]+ resulted in copying the assignments as well. How can I modify the regex to stop at the first white space on each line?

Answer №1

If you're looking to identify instances of this. in your code, you can utilize the following regular expressions:

  • \b(this\.[A-Za-z0-9_]+)(?=\s*=)
  • \b(this\.\w+)(?=\s*=) or
  • ^\s*\b(this\.[A-Za-z0-9_]+)(?=\s*=)

Using these patterns will help you locate the first occurrence of this..

const p = /\b(this\.\w+)(?=\s*=)/gm;
const s = `    this.anchorBillingAddress = this.page.getByTestId(

'billing-address-section'

);
    this.anchorShippingAddress = this.page.getByTestId(

'shipping-address-section'

)

;
    this.anchorBilling = this.page.getByTestId('billing-section');
    this.anchorGeneral = this.page.getByTestId('general-section');
    this.anchorStatistics = this.page.getByTestId('statistics-section');`;

const matches = s.match(p);
if (matches) {
  matches.forEach((match, index) => {
    console.log(`${index}=> ${match}`);
  });
}


Please Note:

  • \s*: Indicates zero or more spaces.
  • \b: Represents a word boundary.
  • (this\.[A-Za-z0-9_]+)(?=\s*=): Captures text from this. up to the first \s or =. The expression [A-Za-z0-9_] is equivalent to \w.
  • (?=\s*=): Utilizes positive lookahead to match the pattern \s*= immediately after this\.[A-Za-z0-9_]+.

Answer №2

To halt at the initial space, you can use this method

^this[^\s]+

The ^ ensures it commences from the beginning and disregards the subsequent this.

Answer №3

If you want to extract all left hand side assignment parts that start with "this.", you can use the regular expression /this\.\S+(?=\s*=)/g

For example, applying this regex to the given text will capture assignments like "this.currentDate", "this.anchorBillingAddress", and others.

const text=`let a = this.currentDate;
this.anchorBillingAddress = this.page.getByTestId('billing-address-section');
// a comment
this.anchorShippingAddress = this.page.getByTestId('shipping-address-section');
let b = this.should.not.be.captured;
console.log(this.property);
this.anchorBilling = this.page.getByTestId('billing-section');
this.anchorGeneral = this.page.getByTestId('general-section');
this.anchorStatistics = this.page.getByTestId('statistics-section');`;

console.log(text.match(/this\.\S+(?=\s*=)/g));

The positive lookahead in the regex pattern, (?=\s*=), ensures that the extracted text is immediately followed by whitespace and an equal sign ("=").

Answer №4

To transfer the lines to their desired location in VS Code, follow these steps:

  • Begin by pressing Ctrl+H to bring up the find/replace dialog

  • If regex support is not already enabled, activate it by pressing Alt+R

  • In the find field, enter ^\s*(this\.\w+).*

  • Input $1 in the replace field:

    https://i.sstatic.net/iV3RpGWj.png

  • Complete the replacements by hitting Ctrl+Alt+Enter.

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

Issue with Web Worker functionality in SvelteKit on Firefox version 106.0.5

I've set up a function in my main file like this: const loadWorker = async () => { const SyncWorker = await import("$lib/canvas.worker?worker"); syncWorker = new SyncWorker.default(); syncWorker?.postMessage({}); ...

Tips for connecting a href to a div id using JQuery for a parallax slider

I'm currently working on the jQuery slider known as Sequence Master Parallax. My goal is to incorporate a menu at the top that allows users to navigate to each slide. However, I am encountering difficulties in linking the href to the div id. I am unsu ...

How can you achieve the effect of "hovering over an image to automatically start playing a muted video within the image itself"?

[![enter image description here][1]][1]I am working with WordPress and Elementor, and I want to create a hover effect where an image triggers a muted video to play within the image area on mouseover. The video should stop playing when the mouse is not hove ...

Disabling ESLint rule in a React application while using WebStorm

Currently, I am working on a React application in WebStorm using the standard setup for React. I have not configured any specific linting rules before, so all error and warning messages that are popping up are due to some default settings. Whenever I execu ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Searching for information in one array using a loop with another array (MongoDB and JavaScript)

I have two arrays that need to be compared for matching elements. let firstArray = [1, 2, 3] let secondArray = [{id:1}, {id:1}, {id:3}] I am trying to create a new array containing objects with the same id. Despite trying different approaches, I am unabl ...

Create various designs for a section of a webpage

My goal is to create a coding playground using flex-box to position different panels. Here is an example in JSBin, with the following html code: <div class="flex-box"> <div class="col" id="html-panel"> <p>html</p> </div& ...

Unable to access the get method of an undefined node.js object

I'm currently working on implementing a new structure and scalability approach for an express application. Challenge: I am looking for a way to automatically load routes without having to define each one in the app.js file. Proposed Solution: I ai ...

Tips for verifying the functionality of your AngularJS controller and troubleshooting any potential issues

Testing my controller functionality has been a challenge. I attempted to use an alert function to check if the controller is working properly, but unfortunately, nothing seemed to happen. JS routerApp.controller('myCtrl', ["$scope", "$http", " ...

creating a one-to-one relationship between two arrays in angular

students:any=[{name:'shariful', id:'1',teacherId:'1'},{name:'Hasan', id:'2',teacherId:'2'},{name:'sohag', id:'3',teacherId:'2'}] teachers:any=[{name:'Robi', ...

Tips on how to highlight a clicked list item:

I'm currently attempting to access the key={1} Element within my li. My goal is to set the activeItem in State in order to compare it with the clicked item later on. If they are equivalent, I want to apply an active class to that specific element. How ...

Is it considered a poor practice to self-instantiate within a static method of a JavaScript class

Do you think this object-oriented JavaScript (TypeScript) code is not well-written? class KYC { public reference; public data = null; constructor(id: string) { this.reference = id ? firestoreAdmin.collection('kyc').doc(id) : fi ...

Ensure that the form is submitted only after confirming it in the modal with react-hook-form

**I am facing an issue with submitting react-hook-form on confirm in a modal component. Whenever the user selects confirm, I need the form to be submitted directly. I have tried writing the modal inside FormSubmitButton. Also, I have tried placing it insi ...

Troubles encountered while generating a title for a tooltip using d3-tip

After successfully creating a chart in a tooltip following the example provided here: https://bl.ocks.org/maelafifi/ee7fecf90bb5060d5f9a7551271f4397, I've encountered an issue with adding a title to it. var tool_tip = d3.tip() .attr("clas ...

What are the steps for utilizing the map function to merge an array or nested array into a div element?

I'm currently developing a recipe box application and have shared the code pen for it: http://codepen.io/capozzic1/pen/gmpVyr?editors=0110. The code snippet is as follows: class RecipeList extends React.Component { constructor(props) { super(p ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Is it necessary for React DOM to utilize className? I find it peculiar that I'm not receiving any alerts or warnings

I've been experimenting with React in a project for several weeks now. It just crossed my mind that I should be using className instead of class in regular DOM and SVG elements, as class is a reserved keyword in JavaScript. Despite this realization, ...

Utilizing Socket.io within secured routes

I'm currently working on a web application that involves user authorization and the ability to chat with others. I've encountered an issue where, despite including e.preventDefault() in my JavaScript code for the submit button, the page still ref ...

Update the text inside a paragraph using jQuery

When attempting to modify two values within a paragraph using jQuery, I encountered an issue where only one value was successfully updated, leaving the other empty. <div class="container"> <p class="lead custom_bg" id="comment"> updateme! ...