Get the characters from a JavaScript string, but make sure to exclude

There is a text string that I need to work with:

TEST:ABCDEGF:18:32

This text includes letters and numbers, but I want to extract all of them excluding the : character.

Previously, I was using the following code successfully:

lines.split(":");

However, I now have a new requirement where I also need to extract the time in full form like 18:32, which means simply using split won't cut it because it only gives me until 18.

So, how can I modify my approach in order to extract the time as well?

For example:

ABCDED:ERERE:18:32

Desired output:

 temp.fields[0] = ABCDED
 temp.fields[1] = ERERE
 temp.fields[2] = 18:32 

Answer №1

If the time is consistently located at the end, you can utilize this method.

function manipulateString(str) {
  var arr = str.split(':');
  var timeSection = arr.splice(-2).join(':'); // remove last 2 elements from array and join them
  arr.push(timeSection);
  return arr;
}

console.log(manipulateString('TEST:ABCDEGF:18:32'));

Answer №2

After investigating the issue thoroughly, I was able to find a solution:

let remainder = elements.splice(3).join(':');

I came across this helpful tip on:

Splitting strings with limits, capturing the remaining string

This workaround is exactly what I needed to achieve my desired outcome.

Special thanks to t.niese for the suggestion and appreciation to all contributors for their input. While multiple solutions were presented, the simplicity of the one provided in the referenced link stood out. If possible, I would acknowledge every response received. +1 to all involved.

Answer №3

Give this a shot

let str = `ANOTHER EXAMPLE:XYZ123AB:MNO:TUVW:xx:34:EFG:45:56:PPP`;;

let n = str.replace(/(\d\d\:\d\d)|\:/g,"$1 ").replace(/ +/g,' ').split(' ');

console.log(n);

Regexp explanation: "\d\d:\d\d" identifies the time in the first group, ":" matches a colon, then only the first group followed by a space "$1 " is output (colons are omitted and unmatched text remains unchanged), and finally (in the 2nd replace) double spaces are changed to single spaces before being split into an array.

Answer №4

To adjust the delimiter (:) in all instances except when it appears between numbers, you can utilize the replace method. Here is an example of how this can be achieved:

const data = "ABCDED:ERERE:18:32";

const arr = data.replace(/:/g, function(match, pos, str){
  const before = str.substring(pos - 2, pos);
  const after = str.substring(pos + 1, pos + 3);

  if(!isNaN(before) && !isNaN(after)){
    return match;
  }else {
    return "|";
  }
}).split("|");

console.log(arr);

Answer №5

After coming across a comment stating that time always appears at the end, I decided to provide a simpler second answer in text format.

temp.fields = [...s.slice(0,-6).split(':'), s.slice(-5)]

let s="ABCDED:ERERE:18:32"

let fields =  [...s.slice(0,-6).split(':'), s.slice(-5)]; 

console.log(fields);

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

Exploring Commitments in React

I'm currently navigating the world of promises and finding it challenging to grasp! My main focus right now is setting up an authentication system for my application. RegisterPage The handleSubmit function in my RegisterPage looks like this: handl ...

Guide to activating the 'Next' button on WP Forms using JavaScript code when certain conditions are fulfilled

Is there a way to adjust the JavaScript code provided so that the visibility of the "Next" button is dependent on whether at least one item in the 'wpforms-icon-choices-item' class has the '.wpform-selected' class on the current page or ...

Challenges in rendering textures

Hello there, I'm encountering an issue with the way a texture is being rendered on an imported OBJ model. Below is an image showing how the texture currently appears: And here is how the texture should actually look when mapped to the object: Here ...

What could be causing the appearance of a Firefox error message during the execution of a Protractor test?

Currently, I am conducting end-to-end testing on an AngularJS application using Protractor. Every time I execute a spec, Firefox launches and closes with a particular message appearing: After that, Firefox starts working properly and the specs run smooth ...

In order to toggle a div property on and off with each click, you will need to use an onclick JavaScript function

I have an HTML button that triggers a JavaScript function when clicked, revealing a hidden div by changing its display property. The current setup is functional and achieves the desired outcome. However, I now wish to modify the functionality so that subs ...

What is the reason for being unable to remove the event listener from a sibling element?

function show1() { console.log("ok1"); document.getElementById("a2").removeEventListener("click", delegate); } function show2() { console.log("ok2"); } function show3() { console.log("ok3"); } function delegate(event) { var flag = event.target ...

Using ng-class in Angular.js with a boolean retrieved from a service: A step-by-step guide

I need to dynamically set a class based on a boolean value that is determined in a service. This example is simplified for readability, but in reality, the boolean would be set by multiple functions within the service. Here is how it would look in HTML: ...

Eliminate a specific choice from a drop-down menu in an Angular application

I am implementing a feature where clicking on a button adds more select drop downs. I want to ensure that the selected options in these new dropdowns do not duplicate any already chosen options. Below is the code snippet used for the select drop down: < ...

What is a more efficient way to avoid duplicating code in javascript?

Is there a way to avoid repeating the same code for different feeds? I have 8 feeds that I would like to use and currently, I am just incrementing variable names and feed URLs. <script type="text/javascript> function showFeed(data, content ...

Can JavaScript be used to save data to a file on a disk?

As a beginner to intermediate programmer exploring AJAX, I was intrigued while learning about JavaScript. It caught my attention that many examples I have come across incorporate PHP for this task. While some may say 'I'm going about it the wrong ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

Custom HTML on Joomla causing carousel to vanish

I've encountered an issue with my Joomla website where my carousel images are disappearing. I have a code snippet from W3 Schools for an automatic banner that works perfectly fine when opened in a browser using Notepad++, but when inserted into a cust ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Tips for retaining focus on the same control following an asynchronous postback

I am experiencing an issue with my 3 textboxes, where one is placed in an update panel that refreshes every 4 seconds. Unfortunately, during the refresh process, the focus on controls outside of the update panel is being lost. I need a solution to maintain ...

What is the best option: using a Javascript template or exploring another

Just starting out in web development. I want to include the same menu on every page of my new website, but I don't want to manually update it in each file whenever there's a change. Is there an easy template engine for JavaScript or another sol ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method. Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080 Here is an image of the console showing ...

Erase the destination pin on Google Maps

I am currently working on a project that involves displaying hit markers on google maps along with a route from start to finish. Although I have successfully displayed the route, I encountered an issue where both the origin and destination have identical ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

Using JQuery to trigger the onchange event for a select tag

I am working with jQuery where I need to append select tags inside a table for each row. I want to add an onChange event for each dropdown on every row. However, the approach I have taken doesn't seem to be working. This is what my jQuery code looks l ...