I'm trying to set up an HTML poster image from some videos URL using Javascript, I can get the full path to the file using "+ element +" but I can't remove the extension at the end.
I tried a few ways but they all generate errors.
"+ element +" will generate this result img/holidays/4ofjuly2.mp4
I need to remove on poster="img/holidays/4ofjuly2.mp4" .mp4 to add .jpg
I tried .replace(/.[^/.]+$/, "")
and .split('.').slice(0, -1).join('.')
function createImagesTag(data){
var imagesdata = JSON.parse(data);
images=imagesdata;
var imagesTag="";
var a=0;
imagesdata.forEach(element => {
if(a==0){
imagesTag+="<video muted preload='none' poster='"+ element +"' width='80%' height='40%' id='images_"+a+"' onclick='changeSelected("+ a +")' class='imagescards' <source src='"+ element +"#t=1.5'type='video/mp4' style='border: 3px solid red;'></video><br />"
}
else{
imagesTag+="<video muted preload='none' poster='"+ element +"' width='80%' height='40%' id='images_"+a+"' onclick='changeSelected("+ a +")' class='imagescards' <source src='"+ element +"#t=1.5' type='video/mp4'></video><br />"
}
a++;
});
document.getElementById("images").innerHTML = imagesTag;
}
You're probably looking for substring.
Check the code below, and if you want more information about reduce, check this link from MDN.
function createImagesTag(data){
const images = JSON.parse(data);
const imageList = images.reduce((acc, el, index) => {
const srcWithoutSuffix = el.substring(0, el.length - 4);
if(index === 0) {
acc+=`<video muted preload='none' poster='${srcWithoutSuffix}'' width='80%' height='40%' id='images_"+a+"' onclick='changeSelected(0)' class='imagescards' <source src='${el}'#t=1.5'type='video/mp4' style='border: 3px solid red;'></video><br />`;
return acc;
}
acc+=`<video muted preload='none' poster='${srcWithoutSuffix}' width='80%' height='40%' id='images_"+a+"' onclick='changeSelected(${index})' class='imagescards' <source src='${el}'#t=1.5' type='video/mp4'></video><br />`
return acc;
}, '');
const imagesHTML = imageList.substr(0, imageList.length - 4);
document.getElementById("images").innerHTML = imagesHTML;
}
I think the problem is with the syntax for <video> tag, please check the format.
<video>
<source src="">
</video>
The JS funcktion replace make a good job for this usecase.
const poster = "img/holidays/4ofjuly2.mp4";
const result = poster.replace(/mp4/g, "jpg");
console.log(result)