最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - removing format of a given image as an string - Stack Overflow

programmeradmin0浏览0评论

let's say we have a variable containing a string representing an image and its format like this:

let pictureLabel = 'picture.jpg';

I want a function to remove the format and return the name only. so I tried this but definitely I need a hand as a beginner :)

Here is what I tried without success. Why and how to fix this code:

let pictureLabel = 'picture.jpg';


function withoutFormat(pictureLabel){

  const formats = ['png', 'jpg', 'jpeg', 'gif']; // defined formats to be remove
  
  formats.forEach(format => {
  
  console.log(pictureLabel.lastIndexOf(`.${format}`))
    
  if(pictureLabel.lastIndexOf(`.${format}`) != -1){
     return pictureLabel.substring(0, pictureLabel.lastIndexOf(`.${format}`));
  
  } 
    
  });
   
}

console.log(withoutFormat(pictureLabel));

let's say we have a variable containing a string representing an image and its format like this:

let pictureLabel = 'picture.jpg';

I want a function to remove the format and return the name only. so I tried this but definitely I need a hand as a beginner :)

Here is what I tried without success. Why and how to fix this code:

let pictureLabel = 'picture.jpg';


function withoutFormat(pictureLabel){

  const formats = ['png', 'jpg', 'jpeg', 'gif']; // defined formats to be remove
  
  formats.forEach(format => {
  
  console.log(pictureLabel.lastIndexOf(`.${format}`))
    
  if(pictureLabel.lastIndexOf(`.${format}`) != -1){
     return pictureLabel.substring(0, pictureLabel.lastIndexOf(`.${format}`));
  
  } 
    
  });
   
}

console.log(withoutFormat(pictureLabel));

Share Improve this question edited May 8, 2020 at 18:42 foxer asked May 8, 2020 at 18:31 foxerfoxer 9012 gold badges7 silver badges21 bronze badges 5
  • U can use regex, indexof or split methods. It is based on your input types. @foxer – Cagri Tacyildiz Commented May 8, 2020 at 19:07
  • What error or inaccurate results are you getting with the new code you just posted? – xdhmoore Commented May 8, 2020 at 19:17
  • 1 I think the problem is your return statement doesn't return from withoutFormat, it returns from the anonymous function format => { ... }. – xdhmoore Commented May 8, 2020 at 19:23
  • If you replace your formats.forEach with a normal for loop (or maybe for format of formats) it will probably work, I think. – xdhmoore Commented May 8, 2020 at 19:23
  • Well, technically for(format of formats) {... – xdhmoore Commented May 8, 2020 at 19:34
Add a ment  | 

7 Answers 7

Reset to default 3

if u will do all types for your files use split and take first element

let pictureLabel = 'picture.jpg';

console.log(pictureLabel.split(".")[0])

but if it will be just for spesific ones use regex

var array=[".png",".jpg"];

console.log("picture.jpg".replace(new RegExp(array.join("|")),""))
console.log("video.mp4".replace(new RegExp(array.join("|")),""))

If you’re using node.js, use path.basename.

Otherwise, Array.prototype.lastIndexOf seems like a good way to get you started.

use lastindexof() method to find the last(.) and remove the string after the (.)

Try this function now.

function withoutFormat(pictureLabel) {

    const formats = ['png', 'jpg', 'jpeg', 'gif']; // defined formats to be remove
    // Code to remove the format and return the name
    let lastIndexOfDot = pictureLabel.lastIndexOf('.');
    let name = pictureLabel.slice(0, lastIndexOfDot);
    let ext = pictureLabel.slice(lastIndexOfDot + 1, pictureLabel.length);
    if (formats.includes(ext))
        return name;
    return 'Image format not defined';
}
let pictureLabel = 'picture.png';
console.log(withoutFormat(pictureLabel));

let pictureLabel = 'picture.jpg';

function withoutFormat(file){
  const formats = ['png', 'jpg', 'jpeg', 'gif'];
  const regex = new RegExp(`.(${formats.join("|")})$`, 'gi');  
  return file.replace(regex, "");
}

console.log(withoutFormat(pictureLabel));

In response to the new question:

The return statement appears to be returning from the anonymous function defined inside formats.forEach(format => {...}). Perhaps the easiest way to fix it would be to use a for (format of formats) { instead of the foreach() function. Then the enclosed return statement will return from the broader-scoped withoutFormat as I think is intended.

For the original question: Try "picture.jpg".replace(/\.(png|jpg|jpeg|gif)$/,'')

Regex breakdown:

  • \. a dot
  • (png|jpg|jpeg|gif) one of the file extensions
  • $ the end of the string

const filename = "demo.heic"
const newFileName = `${filename.split('.')[0]}.jpeg`
console.log(newFileName)

//======== OR ==========================//
 
const filename1 = "image.BMP"
const array = ['bmp', 'BMP', 'pjp', 'jfif', 'heic', 'HEIC']
const checkFileExtension = filename1.split('.').pop()
console.log(checkFileExtension)
if (array.includes(checkFileExtension)) {
  console.log(`${filename1.split('.')[0]}.jpeg`)
}

发布评论

评论列表(0)

  1. 暂无评论