I made a function that removes the last part of the string which will always start from _ and get the integer, but all I get is the text part and not the integer
How can this be achieved?
function splitLast(arg) {
if (arg.includes(".") && arg.includes("_")) {
return parseFloat(arg.split("_").pop())
} else if (arg.includes(".") != true && arg.includes("_")) {
return parseInt( arg.split("_").pop())
} 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')
CodePudding user response:
Probably, you have to use 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')
CodePudding user response:
You could use a regexp and .replace:
function splitLast(value) {
return value.replace(/_.*$/, '');
}
console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
CodePudding user response:
You can use this to remove text from string and only numbers with underscore remains.
var ret = "22.1_no";
var str = ret.replace(/[^0-9\.] /g, "");
console.log("_" str);
