Regular expression: retrieve the text following every colon

Consider the following string:

"abc:12:toto:tata:titi"

To extract each string after ":" using split(), you will get "toto", "tata", and "titi" in this scenario.

Answer №1

My goal is to extract each individual string that comes after a colon:

By utilizing the split() function in conjunction with filter(), we can effectively remove any numerical values from the string.

To exclude the first element, I've implemented the use of splice(1)

const input = 'abc:12:toto:tata:titi';
const res = input.split(':').slice(1).filter(n => isNaN(n) && isNaN(parseFloat(n)));

console.log(res);

[
  "toto",
  "tata",
  "titi"
]

Answer №2

When dealing with colon delimited values, it is important to note that they will always consist of either purely numerical values or purely alphabetical words:

var input = "xyz:45:hello:world";
var results = input.replace(/:\d+/g, "").split(":");
results.shift();
console.log(results);

By using the regex pattern :\d+ for replacement, we can eliminate the numerical elements. After splitting the values by colon, we remove the first element which cannot be a match as it is not preceded by a colon.

Answer №3

To extract words from a string separated by colons, you can utilize the String.prototype.split() method:

const str = 'abc:12:toto:tata:titi';

const words = str.split(':');
console.log(words);

Output:

Array(5) [ "abc", "12", "toto", "tata", "titi" ]

Using regular expressions may not be necessary in this case since the delimiter is constant and simple.

If you specifically want to extract only the alphanumeric strings following a colon, you can do so with:

const str = 'abc:12:toto:tata:titi';

const filteredWords = words.slice(1).filter(word => !isNaN(parseInt(word)));
console.log(filteredWords)

Output:

Array(5) [ "toto", "tata", "titi" ]

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

Using jQuery: in the event that $(this) or a different element loses focus, then

I am looking to execute a function when either the currently active element $(this) or another specific element (e.g.: div#tooltip) loses focus. However, I have not been successful in finding the right approach. I have attempted the following: $(this).add ...

Analyzing the string's worth against the user's input

I need help figuring out how to save user input on a form (email and password) as variables when they click "Register", so that the data can be used later if they choose to click "Login" without using default information. I am working on this project for s ...

Mastering the correct usage of Express middleware functions in routers

Displayed in this instance, are the csrfProtection and parseForm functions being utilized as parameters/callbacks within the GET and POST requests... var cookieParser = require('cookie-parser') var csrf = require('csurf') var bodyParse ...

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...

Tips for assigning the result of a Fetch API call to a variable

Hello everyone! I'm currently working on a project that requires me to retrieve the latitude or longitude of a location using the Google Maps API. However, I am facing an issue with returning values using the Fetch API and its promises. I have succe ...

Data entry and a dropdown menu

Looking to add a dynamic numeric input that changes based on a select box choice. The numeric input will have a specific range based on the selected option from the select box. For instance: If option2 is selected, the numeric input range will be from 2 ...

Using JQuery to append elements and then locate them with the find method does not produce the expected

Hey there, I'm having trouble inserting one DOM element into another. It's something I've done many times before successfully, but for some reason it's not working this time and I can't figure out why. Currently, I am using an Aja ...

When utilizing the map function with an array containing 168 objects in the state of a React application, a freeze of around 1

I encountered an issue when trying to update a property in a state array of objects after executing an axios.put request. Here is my code: States - useEffect //... const [volunteers, setVolunteers] = useState([]); //... useEffect(() => { async fu ...

Avoiding mocking a specific module with jest forever

Our codebase heavily relies on underscore in various parts, and I prefer to avoid mocking it. I'm aware that I can use jest.unmock('underscore'); in each test that utilizes underscore. Is there a method to unmock underscore across all tests ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

The radio button is not appearing correctly in my HTML form

Seeking guidance as a newcomer to html and css. Looking to create a signup form using html and css, but encountering issues with the radio button not displaying in the browser. Unsure of the root cause of the problem. Any assistance would be greatly apprec ...

JavaScript framework that is easily customizable to include support for XmlHttpRequest.onprogress, even if it needs to be emulated

Which JavaScript library or framework offers support for the "onprogress" event for XmlHttpRequest, even if it needs to be emulated using a plugin or extension? Alternatively, which JavaScript framework is the most straightforward to extend in order to add ...

Utilizing setTimout() Method as a Promise in Node.js

I am a beginner in JavaScript and I am working on creating a simple REST API in Node.js for my application. At one point in my code, I need to wait for approximately 5 seconds. I am struggling to understand the difference between using a Promise and a nor ...

Is there a way to showcase a PHP code snippet within JavaScript?

This piece of code contains a script that creates a new div element with a class, adds content to it using PHP shortcode, and appends it to an Instagram section. Check out the image here <script> let myDiv = document.createElement("div"); ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

Tips for splitting a container of specific height into sections measuring 80% and 20%

I am working on a container with a fixed position that I want to split into two halves: 80% and 20% at the bottom. This is what I want it to look like: Click here to see the image. Note: The layout should adjust itself when the window is resized. You c ...

Ways to troubleshoot the logic issue in the loop for my simple login interface

I have been able to successfully implement code that detects when a user enters an incorrect username or password, as well as granting access when the correct credentials are provided initially. However, there seems to be a logic error in my loop that prev ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

Unique custom babel plug-in - JSXElement traversal not supported

I'm currently in the process of creating my very own babel transform plugin. When I examine the AST for a React component using astxplorer.net, I notice that JSXElement appears in the tree as a node. However, when I attempt to log the path for the vi ...

Access an external URL from JSON data simply by utilizing VueJS

I am currently facing a challenge with linking to external URLs. The URL is extracted from JSON and connected to an HTML tag, but I am unable to retrieve the data and link it to the URL when clicking on images. HTML <section class="bg-light page-secti ...