Using Regex in JavaScript to split a string based on a saved pattern

I have a specific sentence to work with:

var sentence="example of+a+string";

My goal is to split the string by the + symbol only when it occurs after the word "of".

When attempting this with the code:

sentence.split(/of(\+)/)

The result splits the string using "of+". How can I achieve the desired outcome of splitting it at the + that follows the word "of", resulting in ["example","a+string"]?

Answer №1

If you want to separate text using specific patterns, try split captures:

 "java+script+regex".split(/(java)\+/)

This will result in

["", "java", "script+regex"]

Alternatively, you can use match:

"java+script+regex".match(/(java)(?:\+)(.+)/).slice(1)
["java", "script+regex"]

Another option is to use replace:

"java+script+regex+java+chrome".replace(/(java)\+/g, "$1@").split("@")
["java", "script+regex+java", "chrome"]

To learn more about mimicking lookbehinds in javascript, check out this post.

Answer №2

Just follow these steps

let text = (" " + sentence).split(/(?=computer[+])/)
               .join("computer")
               .split(/computer[+]/);

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

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

What is the technique for hiding the bottom tab navigator upon leaving a specific screen in React Native version 5?

In the home screen, I want only the bottom tab navigator to be visible, and then hidden until the user returns to the home screen. The example provided below is tailored for working in the App.js file, but my situation is different. const Tab = createBot ...

Tips on how to retrieve an Observable Array instead of a subscription?

Is there a way to modify this forkJoin function so that it returns an observable array instead of a subscription? connect(): Observable<any[]> { this.userId = this.authService.userId; this.habits$ = this.habitService.fetchAllById(this.userId); this.s ...

Fetching various data from MongoDB using NodeJS and presenting it in Jade(Pug) template

I am working with MongoDB collections and need to showcase them on my website, creating a dynamic page that updates automatically. Specifically, I am dealing with team members' information in the database. Here is an example of how my collections loo ...

Tips for keeping a Youtube video playing even after the page is refreshed

Is it possible to save the current position of a Youtube video and have it resume from that point when the page is refreshed, instead of starting from the beginning? I am considering using cookies to store the last position or utilizing GET. Although my w ...

Encountering the "G is undefined" error in Jquery when utilizing string.match

Currently, I am utilizing Jquery version 1.3 and have come across an issue with the code. In Firebug, I am receiving an error message stating: "G is undefined." var product = $("#id :selected"); // This pertains to a dropdown element var prodTxt = ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

"Learn how to update an existing table row and populate its cells with JSON data retrieved from a successful AJAX request without creating a

Currently, I am utilizing CouchCMS. The platform offers a feature known as repeatable regions which essentially generates tables to showcase recurring content. The defined repeatable region looks like this: <cms:repeatable name="item_detail" ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

Creating a state in React and populating the rows of a Material-UI table with fixed data

I have implemented a table in the UI using the material-UI Table component. Initially, I added static data without using the state property of react. Now, I am looking for a way to assign static data to table rows by utilizing the state property. The code ...

Use multer-ftp to change the name of a file

I've been working on uploading a file to an FTP server using multer-ftp. The file is successfully uploaded, but I need to change the name of the file. Is there a way to accomplish this? var upload = multer({ storage: new FTPStorage({ basepath: ...

Encountered an npm compilation error - Unable to locate module: bootstrap-theme.css

I recently updated all the dependencies in my JavaScript program without making any changes to my components or index.js file. However, when I run npm run build I encounter an error with index.js related to bootstrap-theme.css: Failed to compile. Modul ...

What is the best way to define a function that declares and returns an array for global use

I'm attempting to globally declare an array from a function so that it can be accessed by other functions as well. However, I'm unsure how to do this because the code involves a csvtojson converter which complicates things. I'm wondering if ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

Error encountered: Multer does not recognize the field when attempting to upload multiple files in a node.js environment

I would like to upload two files in one request using Node.js and I am utilizing multer for this task. Here is my request in Postman: https://i.sstatic.net/8ZEno.png Additionally, I am using multer in routing: router.post( "/Create", Uploa ...

I would like to take the first two letters of the first and last name from the text box and display them somewhere on the page

Can anyone help me with creating a code that will display the first two letters of a person's first name followed by their last name in a text box? For example, if someone enters "Salman Shaikh," it should appear somewhere on my page as "SASH." I woul ...

Is it possible to restart an animated value in React Native?

I'm facing an issue in my react native app where I have created a simple animated progress bar, but I am unsure how to reset the animation. I attempted the following approach without success: progressValue = 0; How can I reset the animation? Also, w ...

Numerous scripts available for achieving a responsive layout using (window).resize event

I am currently in the process of creating a one-page website with a responsive design. On smaller screens, I have implemented an animated scroll plugin to navigate between content divs, while on larger screens, I am using a plugin to toggle the visibility ...