What is the most effective way to eliminate just the last underscore in a string by employing the

I am currently facing an issue with table cell editing. I have the following code that removes all underscores (_) from a string if it contains "test_1_". However, my requirement is to only remove the last underscore and have the string appear as "test_1".

The JavaScript section of the code needs some expert assistance:

// Obtain edit id, field name, and value
  var id = this.id;
  var split_id = id.split("_");
  var field_name = split_id[0];
  var edit_id = split_id[1];
  var value = $(this).val();

This is how my HTML looks like:

<input type='text' class='txtedit' value='<?php echo date('Y-m-d h:i:s a', strtotime($row['time_in'])); ?>' id='time_in_<?php echo $row['hours']; ?>' >

Now, if you observe closely, the input field's ID appears as 'time_in_', but after splitting, I want 'time_in' to remain while removing only the last underscore.

I hope you understand my point clearly.

Thank you for your valuable help!

Answer №1

In order to remove all occurrences of the "_" character from a given string and obtain an array containing the separate parts on both sides of each "_", you can utilize the split function. However, please bear in mind that this approach will result in an empty string as the last item in the resulting array. To overcome this, you can simply use the pop method to remove the last item from the array before joining the remaining items back together using the join function with "_" as the delimiter:

const inputString = "This_Is_My_String_";
let separatedArray = inputString.split("_");

separatedArray.pop();

const finalString = separatedArray.join("_");

console.log(finalString);

Answer №2

If your intention is to eliminate the final character of the provided string, only if it happens to be underscore (_), then there's a more straightforward option than using the `split()` function. Consider the following snippet:

let updatedValue = this.id.slice(0, -1)

Answer №3

Instead of converting it to an array and rejoining it as a string, there is a more efficient way to achieve the desired result by utilizing string manipulation techniques.

let input = "test_1_";
console.log(input.substring(0, input.lastIndexOf('_')));

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

Issue with triggering the change event for <select> tag

Whenever the selected value of the drop down changes, the following code does not work as expected. Please make corrections if any errors are present. <!doctype html> <html lang="en"> <head> <meta charset="utf-8</scri ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Jesting supplier, infusing elements

I find myself in a complex situation that I will do my best to explain, even if it may seem confusing. Imagine I have a customized provider called actionProvider within the module named core. This provider has the ability to register actions and then exec ...

Saving iFrame as Image using Codemirror and html2canvas

Here are a few experiments I conducted with html2canvas: Fiddle 1 (Using html2canvas): Fiddle 2 (Using html2canvas without Codemirror): Fiddle 3 (Using html2canvas with Codemirror): Fiddle 4 (Using html2canvas with Codemirror): I recently wante ...

Executing a dropdown menu click event using PHP and AJAX

I need to display associated data when a user selects an option from a dropdown list. Below is the code for the dropdown list: <select class="op" name="emp" id ="tab4"> <option value="">--Select--</option> <?php foreach ...

Changing the prototype of a generator function

TL;DR I am looking to enhance a generator function instance by adjusting its prototype, specifically the object received when calling a function*. Imagine I have a generator function: function* thing(n){ while(--n>=0) yield n; } Next, I create a ...

What is the best way to send data back to a separate JavaScript file in ExtJS when working with records in a

I'm currently working on implementing a pop-up editing feature on a grid in extjs4. Progress so far includes successfully transferring the grid record to a popup panel located in a separate JavaScript file using the following code: handler: function( ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

What is the correct way to use getServerSideProps?

Lately, I've been exploring the world of web development by creating a web app using NextJS. While I have some knowledge of the basics in this field, I found myself a bit lost when working with NextJS since I hadn't worked with React before. One ...

When using Multer for file upload, the req.body returns as an empty object while req.file is undefined

I previously shared a problem I encountered while using multer for file upload in the MERN stack. Despite my attempts, I have not yet been able to resolve it. In my app, I am using both body-parser and multer. Here is the order of code in my index.js file: ...

Utilize jQuery to enable click functionality for an entire div within AJAX-loaded content

I have a custom-built website using Wordpress and the posts are loading dynamically. Here is an example of the code I added to the php file for single post: HTML <article> <div class="blog-item-holder"> <div class="featured-ima ...

Display additional images with "Show More" view

I'm looking to create a view similar to the one shown in this image: https://i.stack.imgur.com/AZf61.png Within my FlatList, all the data is being populated including these thumbnails. These thumbnails are stored in an array of objects where I retri ...

In need of assistance with Ember data! Struggling to deserialize JSON into model

Here is the technology stack I'm currently using: Ember 1.10.0 Ember Data 1.0.0-beta.15 Within my application, I have defined a model as shown below: //models//acceptedtask.js import DS from "ember-data"; export default DS.Model.extend({ userAg ...

Avoid unnecessary re-renders in React Redux by ensuring that components do not update when properties are not utilized in their

I'm encountering an issue with a component that keeps re-rendering. I've implemented Redux to handle my states. Within a component, I access a property (isPlaying: bool) from the state using mapStateToProps in various methods of the component, ex ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

What is the best method for uploading an image to the server side using JQuery AJAX and without any additional libraries in an ASP.NET web form

Hey there, I recently discovered a code that allows me to drag and drop an image into a designated zone for display, and it works like a charm. However, despite numerous attempts, I have been unsuccessful in uploading the file. I understand that the path ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

Stop angular schema form's destroyStrategy from deleting any data

After upgrading my Angular app from version 0.8.2 to 0.8.3 of Angular Schema Form (ASF), a significant bug emerged. The application features multi-page forms that utilize prev/next buttons for navigation. A condition is implemented to display only relevan ...