I'm trying to retrieve a YouTube view count for a specific video on my Wordpress site. I'm not a coder but I've managed to get it working using this code:
<div id="viewCount" style="display: inline-block;"></div>
<script>
let getviewCount = () => {
fetch(`https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Cemk32wKN_k&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX`)
.then(response => {
return response.json()
})
.then(data => {
console.log(data);
viewCount.innerHTML = data["items"][0].statistics.viewCount;
})
}
getviewCount();
</script>
The final touch I'd like to add is decimal separators so instead of the number looking like this:
13526897
It looks like this:
13,526,897
Based on some research here I think I need to use a function similar to this:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
But I don't know how to code, so combining these two ideas is beyond my ability right now.
If anyone wouldn't mind showing me how to do it, I'd be extremely grateful!
Thanks
Javascript has built-in functions for this
Intl.NumberFormat() function
It will format the number depending on the user's default browser language.
var number = 1234567890;
console.log(new Intl.NumberFormat().format(number));
Will output
1,234,567,890 for US clients
1.234.567.890 for German clients
let num = '13,526,897';
num = num.replace(/\,/g, '');
num = parseInt(num, 10);
You can create a function if you want to use this piece of code again:
function parseNumber(number) {
return parseInt(number.replace(/\,/g,''), 10);
}
Congrats on your first venture into programming! copy and paste the function definition for numberWithCommas before the word let.
To use the function you added, simply call numberWithCommas with data["items"][0].statistics.viewCount inside the parenthesis.
In all, your new code would look like the following:
<div id="viewCount" style="display: inline-block;"></div>
<script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
let getviewCount = () => {
fetch(`https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Cemk32wKN_k&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX`)
.then(response => {
return response.json()
})
.then(data => {
console.log(data);
viewCount.innerHTML = numberWithCommas(data["items"][0].statistics.viewCount);
})
}
getviewCount();
</script>