Hi,
If I have a string "something12" or "something102".
How would I use regex in javascript to return just the numbers parts??
Malcolm
Hi,
If I have a string "something12" or "something102".
How would I use regex in javascript to return just the numbers parts??
Malcolm
Regular expressions:
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern )
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.
I guess you want to get number(s) from the string. In which case, you can use the following:
// Returns an array of numbers located in the string
function get_numbers(input) {
return input.match(/[0-9]+/g);
}
var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');
alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null
You could also strip all the non-digit characters (\D
or [^0-9]
):
'abc123cdef4567hij89'.replace(/\D/g, '');
// returns '123456789'
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:
item=item.replace('^.*\D(\d*)$', '$1');
if (!/^\d+$/.test(item)) throw 'parse error: number not found';
item=Number(item);
If you're dealing with numeric item ids on a web page, your code could also usefully accept an Element
, extracting the number from its id
(or its first parent with an id
); if you've an Event
handy, you can likely get the Element
from that, too.