How to remove a part of a string which will always be at the last?

UPD: A better solution

You can use parseFloat() function without additional checks and string parsing (it will do it all for you):

function splitLast(arg) {
  if (isNaN(arg.trim()[0])) {
    throw new Error('argument is not valid')
  }

  return parseFloat(arg)
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
console.log(splitLast("a22.1_no"), 'should throw')
console.log(splitLast("  a22.1_no"), 'should throw')

isNaN() check is needed because parseFloat(string) returns:

  1. A floating-point number parsed from the given string (which is exactly what you need)
  2. NaN when the first non-whitespace character cannot be converted to a number (which is an edge-case but we should know about it)

Old solution:

Probably, you have to use the shift() method instead of pop().


The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift


function splitLast(arg) {
  if (arg.includes(".") && arg.includes("_")) {
    return parseFloat(arg.split("_").shift())
  } else if (arg.includes(".") != true && arg.includes("_")) {
    return parseInt(arg.split("_").shift())
  } else {
    throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
  }
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')