I'm trying to print image src with the help of e.target.src
to get the output as 'Person-1.jpg' but instead getting as 'localhost:3000/static/media/Person-1.bb56f19f.png'
const imageSrc = (e) => {
console.log(e.target.src);
}
<img src={require('directory').default} onClick={imageSrc}>
CodePudding user response:
Use console.log(e.target.getAttribute('src'));
.src
returns the URL.
.getAttribute('src'));
returns the source parameter as it is.
CodePudding user response:
If the format is uniform, you can just process the string like so:
// Let's say the e.target.src is "localhost:3000/static/media/Person-1.bb56f19f.png"
const baseString = e.target.src
// Split the string by "/" to return:
// ["localhost:3000", "static", "media", "Person-1.bb56f19f.png"]
// Then pop to get the last value of the array, which is:
// "Person-1.bb56f19f.png"
const fileName = baseString.split('/').pop()
// Then split the filename by "." to return
// ["Person-1", "bb56f19f", "png"]
// Then use a template strign to append the new format with the
// first element of the previous array
const actualFileName = `${fileName.split('.')[0]}.jpg`
// Should be "Person-1.jpg"
console.log(actualFileName)