1

I have the following code to get a string and alert it after removing only the last number. Currently I have the following code. But here, remove all the numbers in the string including numbers where at the middle of the string. But I need to remove only the numbers where at the end of the string.

Ex - String = "ABC_1_XY_20"
     alert -> "ABC_1_XY_"

I need to keep "1" But now I lost it as well. How can I fix this?

$("button").on("click", function(){
  var st = "ABC_1_XY_20".replace(/[\d\.]/g ,'');
  alert(st);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
Pedro Corso
  • 557
  • 8
  • 22
David Johns
  • 1,254
  • 3
  • 19
  • 48
  • 2
    Note that `replace()` has nothing to do with jQuery. I've edited your question title as such. – Rory McCrossan Feb 07 '19 at 10:05
  • 1
    You could also check [this question](https://stackoverflow.com/questions/27690005/remove-trailing-numbers-from-string-js-regexp) and [this one](https://stackoverflow.com/questions/45088488/removing-int-and-float-from-the-end-of-a-string-using-javascript-regex) too. – Pedro Corso Feb 07 '19 at 10:37

2 Answers2

3

To fix this use the $ character class to denote that the match should be made at the end of the string. It also makes the g modifier redundant. You can also use + to repeated number and . characters at the end of the string. Try this:

$("button").on("click", function() {
  var st = "ABC_1_XY_20".replace(/[\d\.]+$/, '');
  console.log(st);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

try to do this, it removes the las digit(\d) from your string

var st = "ABC_1_XY_201".replace(/\d$/ ,'');
  console.log(st);
Álvaro Touzón
  • 1,247
  • 1
  • 8
  • 21