So I have the following string
var str = "Ana has 27 apples";
Is there any function that can return only the number 27 from str
as an integer ?
I have found an old thread here about something like this but it was about Java. However it got me into Regular Expressions .
And I went ahead and tried playing with this but nothing gone as I expected.. This is the last expression I tried before coming here:
var str = "Ana has 27 apples"; var regex = /([0-9])\\d+/; var ret = str.match(regex); console.log(ret);
And it returns 27,2 but I don't want that 2 returned and I definitely do not want it as a string. The thing is that the number is not necessary 27 , its a given number and it can be any integer.
So can it be done with Regular Expressions or is there another ("better") way of doing it without supplimentary lines of code?
And it returns 27,2 but I don't want that 2 returned
See the documentation for match :
it will return an Array containing the entire matched string as the first element, followed by any results captured in parentheses
So the 27
is the whole match and the 2
is from the capture group [0-9]
.
You probably want /(\\d+)/
instead (and then to extract the match from the array with ret[1]
)
I definitely do not want it as a string.
That's what parseInt
, parseFloat
and Unary plus +
are for.
You can use parseInt
in order to convert numeric string to number;
const str = "Ana has 27 apples"; const num = str.match(/\\d+/)[0]; console.log(parseInt(num, 10))
Here you go:
match(/\\d+/)[0]
regex will help you to get number as string
and then use parseInt() to get an integer
.
Check below working example:
var str = "Ana has 27 apples"; var num = str.match(/\\d+/)[0]; console.log(parseInt(num));
Add g
on your REGEXP for a global match
var regex = /([0-9])\d+/g;
Hope this helps :>
var str = "Ana has 27 apples"; var regex = /([0-9])\\d+/g; var ret = str.match(regex); console.log(ret)
A different way to do it from what was provided by the other answers is to just remove all non numeric characters from the string, then what you are left with will be anything numeric.
function numericOnly(str) {
return parseInt(str.replace(/\D+/g,''));
}
Note that this is only useful if you know there is only one number in the string. some example results:
console.log(numericOnly('Ana has 27 apples')); // 27
console.log(numericOnly('Ana has 27 apples and 42 oranges')); //2742
console.log(numericOnly('Ana has no apples')); // NaN
Just modify your code like below
You will get 27 only
var str = "Ana has 27 apples";
var regex = /\d+/;
var ret = str.match(regex);
console.log(ret);
You can just do /(\\d+)/g
which will return all integer groupings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.