0

There are a lot of regex out there but I couldn't find the solution to my specific problem.

Consider these strings:

my street 13a
mystreet 3 B
my street karlos 15A

How can I return those:

my street 13
mystreet 3
my street karlos 15

\d+[a-z,A-Z] matches the case "13A, 13a" and \d+ [a-z,A-Z] matches it with whitespaces. After this I would just use this:

myCutStr = myOriginalString.match(/\d+[a-z,A-Z]/g);
myNewStr = myCutStr.replace(/[^\d]/g, '');
myOriginalString.replace(myCutStr, myNewStr);

But can I somehow combine \d+[a-z,A-Z] and ignore white spaces in that regEx? So that this one \d+[a-z,A-Z] will match all of my kind even with whitespaces?

1 Answer 1

3

A single replace would be enough. That is, replace all the non-digit characters present at the last with an empty string.

string.replace(/\D+$/g, '');

OR

string.replace(/(\d)\D+$/g, '$1');

DEMO

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

4 Comments

Hey, thank you! But what is the difference between the first and the second?
first will remove all the non-digit characters present at the last, it won't care about the previous character. That is, it would remove the whole string if the input is foo bar. But the second one would remove all the non-digit chars at the last of a string only if the string contain a digit char at the start or at the middle.
Either I am doing something wrong, or the second one will also remove the last digit in the string. The first one seems to work, though
that's why i used $1 in the replacement part. $1 refers to chars which are present inside the group index 1.

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.