• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 777
  • Last Modified:

JavaScript/REGEX: Remove Numbers from End of String

Using JavaScript, how can I remove all digits from the end of a string?

alert( zapTrailingNumbers('abc123')  ) // should be "abc"
alert( zapTrailingNumbers('abc123xyz')  ) // should be "abc123xyz"
alert( zapTrailingNumbers('abc0')  ) // should be "abc"
alert( zapTrailingNumbers('abc123xyz2')  ) // should be "abc123xyz"

Open in new window

0
hankknight
Asked:
hankknight
  • 2
2 Solutions
 
David S.Commented:
This should do it:
function zapTrailingNumbers(str) {
  return str.replace(/\d+$/,'');
}

Open in new window

0
 
Terry WoodsIT GuruCommented:
function zapTrailingNumbers(myString) {
  return myString.replace(/\d+$/,'');
}

alert( zapTrailingNumbers('abc123')  ) // should be "abc"
alert( zapTrailingNumbers('abc123xyz')  ) // should be "abc123xyz"
alert( zapTrailingNumbers('abc0')  ) // should be "abc"
alert( zapTrailingNumbers('abc123xyz2')  ) // should be "abc123xyz"
   

Open in new window

0
 
Terry WoodsIT GuruCommented:
haha, snap!
0
 
hankknightAuthor Commented:
Wow, exactly the same answer only seconds apart!  Peer affirmed.  Thank you both.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now