skip to Main Content

trying to get table cell edit fixed i have the following code which if a string supposing has test_1_ then it removes all _ but i only want to remove the last _ and it should look like this test_1

here is the js part which needs some expert touch

 // Get 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();

my html looks like this

<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 notice the input field id looks like id=’time_in_’ but after split i want time_in to remain remove only the last _

hope you get my point?

Thanks for your help

3

Answers


  1. Assuming you want to remove the last character of the string if it’s a _, split() is the long way around. Try this:

    var value = this.id.replace(/_$/, '')

    Login or Signup to reply.
  2. You can split the string at the _ characters, which will remove all the _ characters and return an array of the separate parts on both sides of each _, but this will result in an empty string as the last item in the array. So, then you can pop that last resulting array item off the array and join the resulting array items back together with _, which won’t place one at the end:

    let s = "This_Is_My_String_";
    s = s.split("_");
    s.pop();  // pop the last item off the array
    
    s = s.join("_");
    
    console.log(s);
    Login or Signup to reply.
  3. There is no need to convert it to an array and rejoin it as a string. You can use simple string methods to get the result.

    let id = "test_1_";
    console.log(id.slice(0, id.lastIndexOf('_')));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search