I'm learning JS and want to know what's the most efficient way to extract Integer values from Strings like below:
const String1 = '122,730 views'
const String2 = '2,990 likes'
Output:
122730
2990
Is there a JS function to remove all but numerical values from a String? In this case, parseInt() would just return 122 and 2.
JavaScripts parseInt() function does not know any thousands separator.
You can just simply replace them beforehand.
const String1 = '122,730 views';
const Value1 = parseInt(String1.replace(/,/g, ""));
console.log(Value1);
You can try to use Regex like this:
const regex = /[0-9+]/gm;
const str = `122,730 views`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
P.S. I'm sorry I didn't comment, but It's impossible, because of my low reputation.
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num, 10);
}
console.log('122,730 views'.replace(/[^0-9]/g, ''));
console.log(retnum('122,730 views'));