If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The answers given don't actually match your question, which implied a trailing number. Also, remember that you're getting a string back; if you actually need a number, cast the result:
If you're dealing with numeric item ids on a web page, your code could also usefully accept an
Element
, extracting the number from itsid
(or its first parent with anid
); if you've anEvent
handy, you can likely get theElement
from that, too.For number with decimal fraction and minus sign, I use this snippet:
Update: - 7/9/2018
Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.
Update:
Here's another one with which you can even debugger regexp: Online regex tester and debugger.
Update:
Another one: RegExr.
Update:
Regexper and Regex Pal.
IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:
to:
For example, this code:
generates this array:
I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".
If you really want an array of numbers, you can convert the entire array in the same line of code:
My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:
You could also strip all the non-digit characters (
\D
or[^0-9]
):Regular expressions:
This would return an object with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.
Assuming you're not dealing with complex decimals, this should suffice I suppose.