javascript Regular Expressions

There's a string with multiple user names: "rb40425,Fri Jan 30 11:35:33 2015@ot7293,Fri Jan...."

Desiring to extract only the user names using RegEx in JavaScript, like rb40425 and ot7293.

This is my current attempt:

replace(/,.*/, "");

However, it only retrieves the first user name.

Answer №1

To extract user names from a string, you can split the string at each occurrence of the @ symbol and then use the .map() function to create an array of just the user names by applying a regular expression /,.*$/ that matches everything from the comma onwards.

For example:

var text = "rb40425,Fri Jan 30 11:35:33 2015@ot7293,Fri Jan....";
var users = text.split('@')
               .map( function(item){ return item.replace( /,.*$/, '' ); } );
console.log( users.join('\n') );

If you prefer not to split the string, you can achieve the same result with:

var users = text.replace( /,.*?(@|$)/g, ',' );
console.log( users );

This approach will replace each comma along with all subsequent characters (but as few as possible) until it encounters either an @ symbol or reaches the end of the string.

Answer №2

Here is an example of a regular expression:

/[a-zA-Z0-9]+(?=,|$)/g
  • [a-zA-Z0-9]+ This pattern matches one or more alphabets or digits.

  • (?=,) It checks if the matched characters in the above pattern are followed by a , or end of the string $.

Check out this Regex Demo for more information

For Example:

var string = "rb40425,Fri Jan 30 11:35:33 2015@ot7293,Fri Jan....";
console.log( string.match(/[a-zA-Z0-9]+(?=,|$)/g));
// => ["rb40425", "ot7293"]

string = "d7922,Tue Mar 4 17:28:45 2014@ld7922,Tue Mar 4 17:29:42 2014@rr7323,Tue Mar 4 17:28:45 2014@ld7922";
console.log( string.match(/[a-zA-Z0-9]+(?=,|$)/g));
// => ["d7922", "ld7922", "rr7323", "ld7922"]

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

Fade out a background image using jQuery

I am currently working on customizing a jQuery slider similar to NivoSlider. I want to replace the default images with my own controls. Here is what I have in HTML: <div id="slider" class="nivoSlider"> <img src="img/slider/start1.jpg" alt="" ...

Combining the jQuery Rateyo plugin with AngularJS for rating integration

I've been working on integrating the Rateyo plugin with AngularJS, but I'm facing an issue in extracting the rating value from the directive. Below are the snippets of my code: EDIT: Check out the functional plunker Controller var app = angula ...

Tips for incorporating `new google.maps.Marker()` with `vue2-google-maps` are as follows:1. First

Due to certain reasons, I find myself having to utilize new google.maps.Marker() with vue2-google-maps, but I'm unsure of where to begin as most documentation and tutorials use <GmapMarker ... /> in the HTML section instead. I've attempted ...

Angular.js testing for inject() function runs before the execution of a run phase code block

I am facing a situation where I need to load HTML5 Audio specifically for mobile devices, which requires user interaction like ontouchstart. To achieve this, I have implemented the necessary logic in an Angular run phase to ensure it is executed at the ear ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

Does the functionality of JSON.parse include recursion?

After receiving a JSON string in response, I parse it as follows: ring = JSON.parse(response); However, although ring becomes an object, the property ring.stones is only a string when it should also be an object. To address this issue, if I execute: ri ...

The contents of an Array sourced from a SharedArrayBuffer will consistently be comprised of zeroes

Regardless of my efforts, whenever I create an array from a buffer (no need for sharing), the resulting array contains elements equal to the length of the buffer, with all values being zero. It seems like the documentation on typed arrays in Mozilla doesn& ...

Develop a React npm package with essential dependencies included

I have been working on developing a UI library using React ts. As part of this project, I integrated an external library called draft-js into the package. However, when I attempt to implement my library in another project, I keep encountering errors. Despi ...

The file input modification event is disregarded if the identical filename is selected for upload

In my Vue.js application, I am utilizing Vuetify's v-file-input component. The file uploaded is connected to formData.file and its validation is controlled by the rules prop. <v-file-input :rules="fileValidationRules" v-model="fo ...

Exploring the JsonArray Response entity

Trying to decode my fetch response: fetch('restservices/users/', fetchOptions) .then(function (response) { if (response.ok) { console.log('1'); console.log(response) const responseSjon = response.json ...

Issue with Bootstrap/Bootswatch Dropdown Tab Not Showing Up

I am encountering an issue while trying to implement a tab with a dropdown navigation, similar to the examples shown on Bootswatch. Interestingly, it seems that this functionality is not working properly even on the demo page provided by Bootswatch. My ma ...

The delete button in the "Chip" component of React Material-UI is not functioning as expected

I'm having trouble with the "Chip" control and its "X" button functionality. Unlike the examples shown here: http://www.material-ui.com/#/components/chip Adding the "onRequestDelete" property does include the "X" button, but it doesn't respond t ...

Unusual $http Angular.js POST inquiry

Hey there, I'm facing a peculiar issue in my web development project. I have a table that acts as an input field where users can enter data and then send it back to the Spring Rest API. The data is received as a String and then parsed using the Gson l ...

The video element in HTML5 is not showing up on Safari browsers, but it is functioning properly on Chrome

I have set up a video slider on my webpage. You can view the site The code is functioning perfectly on Chrome and iOS Safari, but there seems to be an issue on desktop browsers. When inspecting the page in Safari, the video elements are present in the HTM ...

Is there a similar effect in jQuery? This is achieved using prototype

Simply click on the comments link. Observe how the comments smoothly appear, as if sliding down. Also, try clicking on 'hide' and see what happens. ...

When implementing $().html, certain impacts of mdui may fade away

I've been exploring the functionalities provided by mdui.org, specifically the panel feature. Initially, I had successfully integrated the codes into the HTML body with no issues. View the code here See the screen capture here This allowed me to to ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...

What is the maximum level of referencing allowed in v-if conditions?

I'm encountering an issue with some markup I have: <div class="form-group" v-if="model.owner.enabled"> The model object in the scope is structured like this: { ... owner: { enabled: true ... } ... } However, Vue is th ...

Creating dynamic movement in Three.js using lineTo and curveTo techniques

As a newcomer to three.js and transitioning from Processing/p5.js, I am accustomed to animating loops. My goal is to create a simple stretching pill shape like the one shown in this GIF: Stretching pill shape I've managed to put together a basic &ap ...