Remove certain numbers from a string based on a condition

I have a couple of String varieties as shown below:

78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180

or

78:27247 PERF create tab state : 1502876879180

I am searching for a regular expression to remove the numbers at the beginning of the string 78:24207.

To achieve something like this:

PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180

or

PERF create tab state : 1502876879180

and then if the string contains two numbers after the :, only take the first number:

PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180

becomes:

PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 

I attempted using this replace(/^\d+\.\s*/, ''); for the initial pattern but it didn't work.

and this expression for the second problem replace(\:.*) but no change occurred in my string.

Any suggestions on what I may be doing incorrectly?

Answer №1

To achieve this, you only need to use one replace function:

var text = '78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180'
var result = text.replace(/^\d+:\d+\s*|(:\s*\d+)\s+\d+$/g, '$1')

console.log(result)

text = '78:27303 PERF tab state created : 1502882663195'
result = text.replace(/^\d+:\d+\s*|(:\s*\d+)\s+\d+$/g, '$1')

console.log(result)

Answer №2

Here's another approach: instead of replacing, use the match function to extract the desired content.

[a-z].*:\s*\d+

This pattern finds a letter followed by any characters up to a colon, then optionally followed by spaces and a number.

document.write(
    '78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180'
    .match(/[a-z].*:\s*\d+/i)
);

Answer №3

To utilize this feature, start by matching and then replacing as demonstrated in the code snippet below:

function manipulateString(input){
var output = input.match(/\d+:\d+ ([\w\s.]*)(:\s*\d+)/g)[0];
console.log(output.replace(/^\d+:\d+ /,''));
}
manipulateString("78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180");
manipulateString("78:27247 PERF create tab state : 1502876879180");

Answer №4

To create the initial design, follow these steps:

replace(/^\d+:\d+\s+/, '');

Next, for the second design pattern:

replace(/(\s+\d+)\s+\d+$/, '$1');

Answer №5

Are you concerned with the specific design? If not, you can easily substitute the initial 9 characters with this code snippet:


 var originalString = "78:27247 PERF create tab state : 1502876879180";
 var result = originalString.replace(/^.{9}/, "");
 console.log(result);

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

vjsf.js library: Dynamic form field display triggered by selection in another field

I have implemented the vjsf library for my vue.js form, as seen here: . I am currently working on a specific functionality where the field memberStatusChange should only be displayed when a certain value of the callDisposition select field is chosen. How ...

Cannot get string.replace to function in Node.js Express server

I am having trouble replacing text in a file with dynamic content using string.replace in node.js and express. It seems to work for strings, but not for data read from the file. fs.readFile('test.html', function read(err, data) { if (err) { ...

Automatically toggle Bootstrap checkbox switch to OFF upon successful completion of AJAX script

On my Employee screen, I have an HTML Form with a Bootstrap Checkbox Switch that toggles the visibility of password change fields. Clicking it reveals or hides the fields accordingly. I'd like to set this switch to "off" when the AJAX script updates ...

What sets apart two pieces of TypeScript code from each other?

When I first started learning TypeScript, I encountered an issue that has me stuck. In my code, there are two versions: in the first version, there is an object called name, and in the second version (which is essentially the same), the variable name has ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

Updating a section of a component using another component

I need to update the Header.vue component from the ConfirmCode Component when the confirm method is called When a user logs in with axios ajax, I want to refresh the li element of the header component Appointment.vue: <send-sms-modal@clickClose="setS ...

Set up an event listener for a specific class within the cells of a table

After spending the last couple of days immersed in various web development resources, I find myself stuck on a particular issue. As someone new to this field, the learning curve is quite steep... Let's take a look at a single row in my project: < ...

Error encountered when pushing Angular data to Django for user login form: 'Unexpected token < in JSON at position 2' while attempting to parse the JSON

I believe the < symbol is appearing because the response is in HTML or XML format. This is the section of my code where the login process is failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.ht ...

Unable to display date array in chart.js labels or x-axis within Django framework

In my Django project, I have a model called EmployeeDayOutput with two columns: output_date (which can be either a datetime or date field) and output_hours (a float). On an HTML page, I am using chart.js to display the data from EmployeeDayOutput, where ou ...

Unlocking request header field access-control-allow-origin on VueJS

When attempting to send a POST request to the Slack API using raw JSON, I encountered the following error: Access to XMLHttpRequest at '' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field acces ...

How to incorporate a hyperlink into an Ajax-generated HTML table

I've successfully used thymeleaf in the past, but I'm having trouble implementing it with JavaScript and Ajax get requests. Essentially, I have a table that is generated dynamically. In my HTML script, an Ajax get request fetches and displays a ...

Switching background colors (green/red) in an HTML void when a specific key is pressed - What's the trick?

Is there a solution available for changing the background color in HTML when a specific button is pressed, like the letter A? I want the color to switch from red to green or green to red when button A is pressed, and I would like it to stay that way even i ...

Regular expressions to eliminate leading zeros from a string, excluding those that are part of decimals

Looking for a JavaScript regex that can remove any leading 0 in a string if the string is an integer. 0 => '' 0000 => '' 001 => 1 0.11 => 0.11 0000.11 => 0.11 11000 => 11000 I've been attempting to solve t ...

The step-by-step guide for replacing the extJs Controller component

I have developed a versatile component that is being utilized across different products. In this case, I have a generic window and window controller which I am customizing to fit our specific product requirements. This is my generic window: Ext.define(&a ...

Is there a way to save the form field as a PDF file using JavaScript, PHP, or any other method

I have this code that uploads a CSV file to an html table. Fiddle Now, I need to be able to download the table in PDF format when a button is clicked. Can anyone assist me with achieving this using either JavaScript, PHP, or any other means? Also, how d ...

Retrieve particular key from document in MongoDB based on provided value

My Document retrieval process looks like this: async findOne(id: string) { return await this.gameModel.findById(id); } async update(id: string, updateGameDto: UpdateGameDto) { const game = await this.findOne(id) // This code snippet prints al ...

What is the best way to arrange arrays in JavaScript?

Let's consider two arrays, X and Y. Our goal is to populate array Z with elements that are the same in both arrays X and Y, positioned at the same indexes. X = [a,b,c], Y = [c,b,a], Z = [b] In addition, we want to fill array P with unique values from ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

Can the button run a Python script with the help of jQuery?

I'm currently working on setting up a website using a RaspberryPi. I've managed to integrate JustGage for reading temperatures and other sensors in real-time. Now, I want to add a button that when pressed will execute a Python script. Here' ...