user3272303 user3272303 - 4 months ago 10
Javascript Question

JQuery Regex Parsing

I have a string defined as:

example = bob_kong_24_male_1234


Using the least amount of lines possible, how can I check whether the last bit(the '1234' from the string) of information is an integer and if it is an integer remove it from the string. So the result would be:

example = bob_kong_24_male


Note that there can be other integers in the string so things can get complicated.

My current solution involves splitting the string into an array using the '_' as the delimiter. Then I check whether the last element is an integer or not and if it is, remove it from the original string. But I feel a quicker/simpler solution exists.

Answer

You could also do that with regex.

var example = "bob_kong_24_male_1234";
example = example.replace(/\d+$/, "");
console.log(example)

That regex will remove the last chars if they are digits.

If the aim is to remove the underscore together, the regex is changed to

/_\d+$/
Comments