1

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D

I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end. The problem I am having is that the format is not the same for the codes. I may have M84.534DAC, or M84.534.

What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:

M84.534D -> I need to pass M84.534

M84.534DAC -> I also need to pass M84.534

Is there any function or regex that will do that?

Thank you in advance to all.

1
  • 1
    There is a regex. $ denotes 'ends with', and combine with the digit operator maybe? /\d+$/ might be the right path Commented Dec 20, 2017 at 21:12

3 Answers 3

4

You can use the regex below. It will remove anything from the end of the string that is not a number

let code = 'M84.534DAC'

console.log(code.replace(/[^0-9]+?$/, ""));

  • [^0-9] matches anything that is not a numer
  • +? Will match between 1 and unlimited times
  • $ Will match the end of the string

So linked together, it will match any non numbers at the end of the string, and replace them with nothing.

Sign up to request clarification or add additional context in comments.

3 Comments

Updated with a description
Works perfectly! As soon as it allows me, I mark it as Solved! I appreciate all the answers! Thank you @user184994 for the clear explanation.
There's no need for the ? modifier since it's anchored at the end of the string.
2

You could use the following expression:

\D*$

As in:

var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);

Explanation: \D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.

1 Comment

Thank you very much for your time to answer and explain. I really appreciate it.
0

Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.

I've used document.write just so we can see the results. You use this whatever way you want.

var testData = [
  'M84.534D',
  'M84.534DAC'
]

regex = /\D+$/

testData.forEach((item) => {
   var cleanValue = item.replace(regex, '')
   document.write(cleanValue + '<br>')
})

RegEx breakdown: \D = Anything that's not a digit + = One or more occurrences $ = End of line/input

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.